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.
Related
To whom it may concern:
Thank you for your time.
Here are some codes about drawing a matplotlib plot with Traditional-Chinese labels and legends which can work well in Colab.
import matplotlib as mpl,matplotlib.font_manager as mf,matplotlib.pyplot as plt
!wget -O TaipeiSansTCBeta-Regular.ttf https://drive.google.com/uc?id=1eGAsTN1HBpJAkeVM57_C7ccp7hbgSz3_&export=download
mf.fontManager.addfont('TaipeiSansTCBeta-Regular.ttf')
mpl.rc('font',family='Taipei Sans TC Beta')
lg=("明度高","\n亮度高","頻率高","\n摩擦力小","密度大")
xt=("純墨條","高筋麵粉","在來米粉","鹽","洗碗精","小蘇打粉","酵母")
a=(-1.06166376,-2.56410256,-15.21126761,-19.04761905,35.2941176470)
b=(0,0,-9.15492958,-42.85714285714285714,29.4117647058)
c=(-6.67539267,-15.38461538,-45.49295775,-47.61904762,17.6470588235)
d=(-9.08958697,-20.5128205,15.21126761,9.52380952,11.7647058823)
e=(-7.86794648,-17.94871795,0,-17.94871795,11.7647058823)
f=(-3.25770797,-7.69230769,-6.05633803,-52.38095238,-5.882352941176)
x=(0,0,0,0,0)
yd=(x,a,b,c,d,e,f)
fig,ax=plt.subplots(figsize=(4,5),dpi=300)
for i in range(0,len(xt)):
ax.plot(lg,yd[i],label=xt[i],marker="o")
ptxk=["x-large","k"]
ax.tick_params(axis="x",labelsize=ptxk[0],colors=ptxk[1])
ax.tick_params(axis="y",labelsize="small")
ptt=["『定期定額』vs『定期定額逢低加碼』","x-large","k"]
ptlyl=["各\n變\n因\n較\n無\n添\n加\n墨\n百\n分\n比\n變\n化\n率\n(%)","x-large","darkcyan"]
plt.title(ptt[0],fontsize=ptt[1],color=ptt[2],y=-0.25)
ax.set_ylabel(ptlyl[0],fontsize=ptlyl[1],color=ptlyl[2],rotation=0)
ax.set_yticks([*range(-50,71,10)])
ax.yaxis.set_label_coords(-0.17,0.05)
ax.legend(fontsize="large")
ax.set_axisbelow(True)
plt.grid()
plt.show()
The words in labels and legends only work well with the font called "TaipeiSansTCBeta" like the following picture.
(https://i.stack.imgur.com/CJfas.png)
Could the font be changed to another one like "DFKai-SB", or it only supports "TaipeiSansTCBeta"?
Some information on the internet about this is to add the codes below to line 2, and delete the codes about !wget, font_manager, and mpl.rc. But it doesn't work at all by displaying blank blocks.
mpl.rcParams['font.family'] = 'DFKai-SB'
(https://i.stack.imgur.com/EmMdL.png)
Would you please inform some demonstrations about the problem, or giving some clues to figure out how it works?
So far haven't found any answer to change to another Chinese font in Colab with matplotlib. It's highly appreciate for your guidance.
Best wishes and great thanks,
wish you have a happy new year.
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 having a baffling issue with saving figures with a specified line alpha in matplotlib. I would really appreciate any input. I found this previous thread but changing the rasterization does not seem to fix the issue.
Here's the minimal example I have of where this issue shows up:
import numpy as np
import matplotlib.pyplot as plt
arr = np.random.randn(10000, 2)
plt.plot(arr[:,0], arr[:,1],alpha=.09, color='black')
plt.savefig('dots_vector.pdf')
plt.show()
In the the display window, it looks like the following (what I want):
However, when I save it as a PDF or PNG, it looks like the following:
Note, I've tried the following setting:
ax.set_rasterized(True)
As that's what the previous thread suggested, but this does not fix the problem.
Bizarrely, when I change the marker type of the line, to the following:
plt.plot(arr[:,0], arr[:,1], 'o', alpha=.09, color='black')
The alpha seems to behave exactly as expected either as a PDF or a PNG, seen here:
Any ideas would be greatly appreciated on how to get the alpha to save properly for the line plot, as I'm pretty stumped.
I have the following piece of code to create axis labels with German umlauts:
plt.xlabel('Daten')
plt.ylabel(r'$H\ddot{a}ufigkeit$')
which basically works, and prints the a-umlaut correctly, But the font of the x and y labels are now different, as the x label is printed in math mode. Changing the second line to
plt.ylabel(r'$\textrm{H\ddot{a}ufigkeit}$')
should work as far as I know (in order to create a rm like font instead of the math mode font), but gives a python error:
matplotlib.pyparsing.ParseFatalException: Expected end of math '$'
How can I fix this issue in order to have the same font on both axis, but with umlauts possible?
The non-math umlaut is \":
plt.ylabel(r'H\"{a}ufigkeit')
If you need \ddot only put the $ around that:
plt.ylabel(r'H$\ddot{a}$ufigkeit')
As an aside, the \textrm command only works in text mode. The math-mode equivalent is \mathrm:
plt.ylabel(r'$\mathrm{H\ddot{a}ufigkeit}$')
UPDATE
All of the above assume that you have told matplotlib to render with tex. To do this, add the following at the top of your code:
import matplotlib.pyplot as plt
plt.rc('text', usetex=True)
I'm trying to use Matplotlib & Python in Xcode to generate scientific graphics. My boss would like them to be in LaTeX with matching fonts. I know you can modify the fonts in python with something like this:
from matplotlib import rc
rc('font',**{'family':'serif','serif':['Computer Modern Roman']})
rc('text', usetex=True)
Unfortunately, opening or saving the figure with plt.show() or plt.savefig() gives a string of errors, eventually leading to OSError: [Errno 2] No such file or directory.
I know "Google is your friend", but I haven't managed to find anything on how to go about solving this. Any help would be greatly appreciated.
I usually find it easiest to directly specify the font file I'm after. Here's an example:
import matplotlib.pyplot as plt
import matplotlib.font_manager
from numpy import *
# cmunso.otf is a randomly selected font in my tex installation
path = '/usr/local/texlive/2012/texmf-dist/fonts/opentype/public/cm-unicode/cmunso.otf'
f0 = matplotlib.font_manager.FontProperties()
f0.set_file(path)
plt.figure()
plt.xlim(0,1.)
plt.ylim(0,1.)
d = arange(0, 1, .1)
plt.plot(d, d, "ob", label='example')
plt.text(.5, .1, 'text.. abcdef', fontproperties=f0, size=30)
plt.xlabel("x label", fontproperties=f0)
plt.legend(prop=f0, loc=2)
I'm not a font expert, but I think the reason this is easier is that font selection often has a cascading set of defaults for when the way you specify the font doesn't exactly match the way the system does. The file, though, is easy to find and specify exactly (though it's obviously less portable).
Note that for xlabel and text the keyword is fontproperties and for legend it's prop.