77

I am using matplotlib together with latex labels for the axis, title and colorbar labels

While it works really great most of the time, it has some issues when you have a formula using \text.

One really simple example.

from matplotlib import pyplot as plt
plt.plot([1,2,3])
plt.title(r"$f_{\text{cor, r}}$")

plt.show()

This will result in an error message like:

IPython/core/formatters.py:239: FormatterWarning: Exception in image/png formatter: 
f_{\text{1cor, r}}
   ^
Unknown symbol: \text (at char 3), (line:1, col:4)
  FormatterWarning,

Is there an easy way to use \text in there?

1

3 Answers 3

102

\text won't work because it requires the amsmath package (not included in mathtext - the math rendering engine of matplotlib). So you basically have two options:

  • use latex based font rendering
from matplotlib import pyplot as plt
import matplotlib as mpl
mpl.rcParams['text.usetex'] = True
mpl.rcParams['text.latex.preamble'] = [r'\usepackage{amsmath}'] #for \text command
plt.plot([1,2,3])
plt.title(r"$f_{\text{cor, r}}$")
plt.show()
  1. use mathtext but use \mathrm instead of \text
from matplotlib import pyplot as plt
import matplotlib as mpl
mpl.rcParams['text.usetex'] = False  # not really needed
plt.plot([1,2,3])
plt.title(r"$f_{\mathrm{cor, r}}$")
plt.show()

The latter approach creates a figure like enter image description here
Be aware that unlike with the \text command, spaces inside the \mathrm environment are not respected. If you want more space between the variables you have to use latex style commands (\<space>, \;, ...).

Sign up to request clarification or add additional context in comments.

6 Comments

Thank you! Especially for the actual explanation why it behaves like that.
If you want to export your plot as pgf you also need mpl.rcParams['pgf.preamble'] = [r'\usepackage{amsmath}']
@DanielBöckenhoff Gnaaarrrrrr... or in cases like mine, when you uncomment fig.savefig('name.pgf') and the error pops up, you need both, text.latex.preamble and pgf.preamble set. E.g. add plt.rcParams.update({ "text.latex.preamble": plt.rcParams["pgf.preamble"] }) You let me on the right track! Thank you!
When I try the first, I get : ValueError: Key text.latex.preamble: Could not convert ['\\usepackage{amsmath}'] to str. Do you know what the problem might be or how to fix it?
@RylanSchaeffer In case you or anyone else needs this, to resolve this issue, just remove the string from this list. That is, do:mpl.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}'
|
3

One option is to let matplot lib use LaTeX directly for your text rendering (rather than the mathtext implementation that matplotlib provides).

import matplotlib as mpl
mpl.rcParams['text.usetex'] = True
# (create your plot as before)
plt.title(r"$f_{\mathrm{cor, r}}$")

This requires a fully working LaTeX installation. I can't seem to get it to recognise \text, but \mathrm does work (for 'roman family' font) just fine.

3 Comments

Sure, this solves the problem, though often I would like to keep normal rendering for the rest of it.
yes, I agree (and generally try to avoid full LaTeX when plotting if I can). It seems that I was wrong about the mathrm environment requiring the text.usetex config setting - @Jakob's answer shows that it is implemented in mathtext.
\mathrm doesn't preserve spaces
3

If you use Jakob's method but get:

ValueError: Key text.latex.preamble: Could not convert ['\usepackage{amsmath}'] to str

change the list:

mpl.rcParams['text.latex.preamble'] = [r'\usepackage{amsmath}']

to string:

mpl.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.