I noticed the following issue when plotting axis labels and text in matplotlib with tex enabled, specifically when the font size is set to small integer values. See the code below.
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rc('text', usetex=True)
f,ax = plt.subplots(dpi=200)
ax.set_axis_off()
for i in range(3,8):
ax.text(0.15,0.05*i,r'fontsize=%d$\pm0.1:$'%i,fontsize=i)
ax.text(0.35,0.05*i,r'$E_E$',fontsize=i-0.01)
ax.text(0.4,0.05*i,r'$E_E$',fontsize=i)
ax.text(0.45,0.05*i,r'$E_E$',fontsize=i+0.01)
ax.set_ylim([0,0.5])
plt.show()
This produces:
Notice that when the font size is 5, the subscript is more or less the same size as the normal text. More subtle issues also persist for font sizes of 6 and 7. Adding ±0.01 fixes it, but it's still kinda weird and annoying. Does anybody know what's going on here or how it might be fixed?
Related
I would like to set the lsatex font for my plots with the usual rc parameters setting, but I would like to keep the original font only for the labels (that means I don't want numbers to be displayed in math mode).
Actually I have a logarithmic scale.
The standard python font I'm referring to is the one in the picture below (while with rc I set the standard font as the Computer Modern)
To use the latex font to name your axes while keeping the standard font for your ticks, you can directly use the latex font in the xlabel and ylabel functions.
The code can then be written as:
import matplotlib.pyplot as plt
import numpy as np
N_points=100
x=np.arange(N_points)
y=np.arange(N_points)
plt.plot(x,y)
plt.ylabel(r'$LaTeX\ font\ y-axis$')
plt.xlabel(r'$LaTeX\ font\ x-axis$')
plt.show()
And the output of this code gives:
I use latex in matplotlib by setting
plt.rcParams.update({'mathtext.fontset': 'stix'})
plt.rcParams.update({'font.family': 'STIXGeneral'})
I am using the letter $\ell$ very often in my research and there is a small detail bothering me. As you can see below, matplotlib renders the symbol with the little loop smaller and the letter more slanted. To me it almost looks like a vertically stretched $e$. I tried using the "\mathrm{\ell}" command instead but it did not change anything.
Is there any way I could get the symbol to look normal?
PS: it looks like stackoverflow is not detecting the math mode $ for some reason. If you know how to fix it (or if I am doing something wrong) please point it out or edit the question. Thanks!
The reason is the font you are using in matplotlib. With the following settings, for example, you get the same letter as in overleaf:
import matplotlib.pyplot as plt
import numpy as np
# Example data
t = np.arange(0.0, 10, 1)
s = np.arange(0.0, 10, 1)
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
plt.xlabel(r'$\ell$', fontsize=30)
plt.ylabel(r'$\ell$', fontsize=30)
plt.plot(t, s)
plt.show()
You get:
However, In Jupyterlab I could not reproduce. It used the overleaf fonts even with your settings.
This proved to be the simplest solution for me. Thanks the others for pointing out the font being the issue.
Rather than
plt.rcParams.update({'mathtext.fontset': 'stix'})
plt.rcParams.update({'font.family': 'STIXGeneral'})
I now write the first line as
plt.rcParams.update({'mathtext.fontset': 'cm'})
which works like charm. This is helpful if you are someone like me not using TeX but just the mathtext matplotlib built-in function.
In matplotlib, one can easily use latex script to label axes, or write legends or any other text. But is there a way to use new fonts such as 'script-r' in matplotlib? In the following code, I am labelling the axes using latex fonts.
import numpy as np
import matplotlib.pyplot as plt
tmax=10
h=0.01
number_of_realizations=6
for n in range(number_of_realizations):
xpos1=0
xvel1=0
xlist=[]
tlist=[]
t=0
while t<tmax:
xlist.append(xpos1)
tlist.append(t)
xvel1=np.random.normal(loc=0.0, scale=1.0, size=None)
xpos2=xpos1+(h**0.5)*xvel1 # update position at time t
xpos1=xpos2
t=t+h
plt.plot(tlist, xlist)
plt.xlabel(r'$ t$', fontsize=50)
plt.ylabel(r'$r$', fontsize=50)
plt.title('Brownian motion', fontsize=20)
plt.show()
It produces the following figure
But I want 'script-r' in place of normal 'r'.
In latex one has to add the following lines in preamble to render 'script-r'
\DeclareFontFamily{T1}{calligra}{}
\DeclareFontShape{T1}{calligra}{m}{n}{<->s*[2.2]callig15}{}
\DeclareRobustCommand{\sr}{%
\mspace{-2mu}%
\text{\usefont{T1}{calligra}{m}{n}r\/}%
\mspace{2mu}%
}
I don't understand how to do this in matplotlib. Any help is appreciated.
Matplotlib uses it's own hand-rolled (pure Python) implementation of TeX to do all of the math text stuff, so you absolutely cannot assume that what works in standard LaTeX will work with Matplotlib. That being said, here's how you do it:
Install the calligra font so that Matplotlib can see it, then rebuild the font cache.
Lots of other threads deal with how to do this, I'm not going to go into detail, but here's some reference:
Use a font installed in a random spot on your filesystem.
How to install a new font into the Matplotlib managed font cache.
List all fonts currently known to your install of Matplotlib.
Replace one of Matplotlib's TeX font families with your font of choice.
Here's a function I wrote a while ago that reliably does that:
import matplotlib
def setMathtextFont(fontName='Helvetica', texFontFamilies=None):
texFontFamilies = ['it','rm','tt','bf','cal','sf'] if texFontFamilies is None else texFontFamilies
matplotlib.rcParams.update({'mathtext.fontset': 'custom'})
for texFontFamily in texFontFamilies:
matplotlib.rcParams.update({('mathtext.%s' % texFontFamily): fontName})
For you, a good way to use the function would be to replace the font used by \mathcal with calligra:
setMathtextFont('calligra', ['cal'])
Label your plots, for example, r'$\mathcal{foo}$', and the contents of the \math<whatever> macro should show up in the desired font.
Here's how you'd change your label-making code:
plt.ylabel(r'$\mathcal{r}$', fontsize=50)
and that should do it.
I'm trying to plot a matrix in a matplotlib figure. it seems that it requires using tex for all text to make it work.
However when I do this, it changes the fonts of all the rest of the figure. I want to use my regular matplotlib font for everything. I tried to fix it by overriding the font used with plt.rc("font",**{'family':'sans-serif','sans-serif':['Arial']}) but it does nto work:
plt.figure()
plt.rc("font",**{'family':'sans-serif','sans-serif':['Arial']})
plt.rc('text', usetex=True)
my_matrix = r"$\left(\begin{array}{ll} 2 & 3 \\ 4 & 5 \end{array} \right)$"
plt.plot([1,2,3],[1,2,3])
plt.title(my_matrix)
plt.show()
how can I use tex for the matrix and not change the rest of the fonts set in my matplotlibrc file?
is it possible in matplotlib to have a textbox with different font sizes within one string?
Thanks for help
I don't think this can be done without using the LaTeX text renderer. To use this do,
from matplotlib import rcParams
rcParams['text.usetex'] = True
Then you can print multi-fontsize strings using standard LaTeX syntax, e.g.
from matplotlib import pyplot as plt
ax = plt.axes()
ax.text(0.5, 0.5, r'{\tiny tiny text} normal text {\Huge HUGE TEXT}')
Sometimes the LaTeX font renderer isn't ideal (e.g. note that tick-label fonts are different than normal MPL tick labels), but it is certainly more flexible.