I have to make a figure in python. I need it to use the font Palatino. I downloaded the font here. I placed it under *\matplotlib\mpl-data\fonts\ttf (which turned out to be useless since I had to provide full path to make it work).
Using the following lines allows me to use the font:
prop = fm.FontProperties(fname='C:/Users/MyPC/pyApp/venv/Lib/site-packages/matplotlib/mpl-data/fonts/ttf/Palatino-Roman.ttf')
mpl.rcParams['font.family'] = prop.get_name()
Yay.
Now when I want to use Latex in matplotlib,
rc('text',usetex=True)
the font is now not the one I want. I tried to follow the official page about that and instead use:
rc('font',**{'family':'serif','serif':['Palatino']})
rc('text', usetex=True)
but I cannot see any difference. I tried all possibilities and it looks like the same font.
What am I doing wrong? Perhaps its the latex side that's lacking the required font package...
You can load any latex packages when using rc('text',usetex=True)
You can add this in your code:
plt.rcParams['text.latex.preamble'] = [r'\usepackage{palatino, mathpazo}']
Related
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.
How do I set latex package options in python?
I am trying to setup siunitx. I don't understand how to set options. This also applies to the matplotlibrc directly.
The following does not work.
import matplotlib as mpl
mpl.rc('text', usetex=True)
mpl.rcParams['text.latex.preamble'] = '\usepackage[range-units = single,range-phrase={-}]{siunitx}'
## using the following instead of the previous line works...
# mpl.rcParams['text.latex.preamble'] = '\usepackage[range-units = single]{siunitx},\sisetup{range-phrase={-}}'
import numpy as np
import matplotlib.pyplot as plt
x=np.linspace(1,100,1)
y=x
fig=plt.figure()
ax=fig.add_subplot(111)
ax.plot(x,y,label=r'\SIrange{0}{1}{\metre\per\second}')
ax.legend(loc=0)
Since the code snippet works, I would suggest that it is due to the use of the comma. I tried \, or ',' without luck. I tried it on Mac in a jupyter notebook.
In the default matplotlibrc it says
#text.latex.preamble : ## IMPROPER USE OF THIS FEATURE WILL LEAD TO LATEX FAILURES
## AND IS THEREFORE UNSUPPORTED. PLEASE DO NOT ASK FOR HELP
## IF THIS FEATURE DOES NOT DO WHAT YOU EXPECT IT TO.
## preamble is a comma separated list of LaTeX statements
## that are included in the LaTeX document preamble.
## An example:
## text.latex.preamble : \usepackage{bm},\usepackage{euler}
## The following packages are always loaded with usetex, so
## beware of package collisions: color, geometry, graphicx,
## type1cm, textcomp. Adobe Postscript (PSSNFS) font packages
## may also be loaded, depending on your font settings
Unfortunately I cannot find any information on the proper usage of this option besides what is specified in the comments...
Any ideas?
I would expect that it helps to enclose the preamble string in a list.
mpl.rcParams['text.latex.preamble'] = ['\usepackage[range-units=single,range-phrase={-}]{siunitx}']
I'm trying to use a custom ttf font not installed in the system for text element in the matplotlib figure.
with plt.style.context('mplparams.mplstyle'):
plt.plot(np.sin(np.linspace(0, 3 * np.pi)), '-o')
I know I can change the text properties with FontManager but I'm looking for a solution which only involves an external config file.
At the moment I only know that i can change font.sans-serif to a font name, not font path.
Is this possible?
The font to be used has to be known to the Fontmanager, otherwise you cannot get it into the plot. In order to specify a font through rcParams this font must be found in a folder matplotlib would look for it. In case you don't want to install anything, you may copy the .ttf file to the matplotlib font folder. In my case this is
python\Lib\site-packages\matplotlib\mpl-data\fonts
Then you need to clear the font.chache. Find out its path via print(matplotlib.get_cachedir()) and delete the fontList files. (Or make a backup first if you like).
Then run your script which has the rcParam specified
font.sans-serif : <name of font>
or use
plt.rcParams['font.sans-serif'] = "<name of font>"
Also see this question.
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.
I want to generate high-quality diagrams for a presentation. I’m using Python’s matplotlib to generate the graphics. Unfortunately, the PDF export seems to ignore my font settings.
I tried setting the font both by passing a FontProperties object to the text drawing functions and by setting the option globally. For the record, here is a MWE to reproduce the problem:
import scipy
import matplotlib
matplotlib.use('cairo')
import matplotlib.pylab as pylab
import matplotlib.font_manager as fm
data = scipy.arange(5)
for font in ['Helvetica', 'Gill Sans']:
fig = pylab.figure()
ax = fig.add_subplot(111)
ax.bar(data, data)
ax.set_xticks(data)
ax.set_xticklabels(data, fontproperties = fm.FontProperties(family = font))
pylab.savefig('foo-%s.pdf' % font)
In both cases, the produced output is identical and uses Helvetica (and yes, I do have both fonts installed).
Just to be sure, the following doesn’t help either:
matplotlib.rc('font', family = 'Gill Sans')
Finally, if I replace the backend, instead using the native viewer:
matplotlib.use('MacOSX')
I do get the correct font displayed – but only in the viewer GUI. The PDF output is once again wrong.
To be sure – I can set other fonts – but only other classes of font families: I can set serif fonts or fantasy or monospace. But all sans-serif fonts seem to default to Helvetica.
Basically, #Jouni’s is the right answer but since I still had some trouble getting it to work, here’s my final solution:
#!/usr/bin/env python2.6
import scipy
import matplotlib
matplotlib.use('cairo')
import matplotlib.pylab as pylab
import matplotlib.font_manager as fm
font = fm.FontProperties(
family = 'Gill Sans', fname = '/Library/Fonts/GillSans.ttc')
data = scipy.arange(5)
fig = pylab.figure()
ax = fig.add_subplot(111)
ax.bar(data, data)
ax.set_yticklabels(ax.get_yticks(), fontproperties = font)
ax.set_xticklabels(ax.get_xticks(), fontproperties = font)
pylab.savefig('foo.pdf')
Notice that the font has to be set explicitly using the fontproperties key. Apparently, there’s no rc setting for the fname property (at least I didn’t find it).
Giving a family key in the instantiation of font isn’t strictly necessary here, it will be ignored by the PDF backend.
This code works with the cairo backend only. Using MacOSX won’t work.
The "family" argument and the corresponding rc parameter are not meant to specify the name of the font can actually be used this way. There's an (arguably baroque) CSS-like font selection system that helps the same script work on different computers, selecting the closest font available. The usually recommended way to use e.g. Gill Sans is to add it to the front of the value of the rc parameter font.sans-serif (see sample rc file), and then set font.family to sans-serif.
This can be annoying if the font manager decides for some obscure reason that Gill Sans is not the closest match to your specification. A way to bypass the font selection logic is to use FontProperties(fname='/path/to/font.ttf') (docstring).
In your case, I suspect that the MacOSX backend uses fonts via the operating system's mechanisms and so automatically supports all kinds of fonts, but the pdf backend has its own font support code that doesn't support your version of Gill Sans.
This is an addition to the answers above if you came here for a non-cairo backend.
The pdf-backend of matplotlib does not yet support true type font collections (saved as .ttc files). See this issue.
The currently suggested workaround is to extract the font-of-interest from a .ttc file and save it as a .ttf file. And then use that font in the way described by Konrad Rudolph.
You can use the python-package fonttools to achieve this:
font = TTFont("/System/Library/Fonts/Helvetica.ttc", fontNumber=0)
font.save("Helvetica-regular.ttf")
As far as I can see, it is not possible to make this setting "global" by passing the path to this new .ttf file to the rc. If you are really desperate, you could try to extract all fonts from a .ttc into separate .ttf files, uninstall the .ttc and install the ttfs separately. To have the extracted font side-by-side with the original font from the .ttc, you need to change the font name with tools like FontForge. I haven't tested this, though.
Check if you are rendering the text with LaTeX, i.e., if text.usetex is set to True. Because LaTeX rendering only supports a few fonts, it largely ignores/overwrites your other fonts settings. This might be the cause.