matplotlibrc and latex package setup - python

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}']

Related

matplotlib + latex + custom ttf font

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}']

Latex font in matplotlib - Script-r

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.

eps export issue with Python and matplotlib

I am having problems while exporting eps files from matplot lib. I want to edit in Corel Draw an eps file that was exported from matplotlib using, for example:
plt.savefig('test01.eps', format='eps', dpi=600)
After opening the file in corel, I get the following image
as it can be seen, there is a problem with letters. They are imported with wrong size and positioning; also they are converted to curves (although I have explicitly said to Corel to import the as text).
Importing the eps file with Microsoft Words gives the same results. It seems to be a matplotlib problem.
I have tried changing to Qt4Agg using
mpl.use('Qt4Agg')
font = {'family' : 'Times New Roman','weight' : 'normal','size': 12}
mpl.rc('font', **font)
but it doesn't work...
Anyone having the same issue?
Add these two lines:
matplotlib.rcParams['text.usetex'] = True
matplotlib.rcParams['text.latex.unicode'] = True

Disable tex interpreter in matplotlib

I would like to produce plots using matplotlib (through anaconda-spider installed on os x yosemite) and put labels on it not interpreted by tex.
Here is the sample code:
# -*- coding: utf-8 -*-
import matplotlib.pyplot as pp
my_rc_param = {'text.usetex': False}
pp.figure()
pp.rcParams.update(my_rc_param)
pp.plot(range(10))
pp.xlabel('$x$')
I would like to see exactly the string $x$ as x label. In turn, I get the math-mode latex x.
I have also tried, unsuccessfully, to put the following preamble:
from matplotlib import rc
rc('text', usetex=False)
Is there a way to force a plain interpreter?
Or should I consider this as a bug?
You are not getting any latex mode. You are simply using the mathtex feature of matplotlib. Using latex is a different thing. I checked whether it is possible to switch off mathtex for matplotlib, and there is a quiet recent issue on this (see here). However, the way to sort out this problem consist is avoiding the math just escaping the $ symbol with '\':
pp.xlabel('\$x\$')
Just remove all the stuff related to the text.usetex as you are trying to do a complete different thing here.

How to create 'normal' looking axis labels using latex in matplotlib

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)

Categories

Resources