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

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)

Related

Matplotlib version of latex command "\ell" looking extra-slanted

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.

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.

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.

displaying charts from python executables in shell

I'm using python 2.7 on Ubuntu to draw charts from text files containing data.
My point is, when using python executables in shell, I have no problem recording plots, but if I want them shown on my screen instead I have to go through the graphic interface. If possible, I would very much like to skip that part and get a dynamic display that I can interact with (as if I were to run my script from a python shell)!!
a MWE of what i'm doing is :
MWE
import numpy as np
import matplotlib.pyplot as plt
with open('filename','r') as myfile:
DATA = np.genfromtxt(myfile,unpack=True)
fig = plt.figure()
... my plot configuration ...
plt.savefig("image_name"+'.png')
plt.close()
end of MWE
Using this script image_name.png appears in my repertory. I tried replacing the last 2 lines with plt.plot() and plt.draw() but nothing happened.
Many thanks!
Michel
(edited)

python latex font xcode

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.

Categories

Resources