\text does not work in a matplotlib label

PythonMatplotlib

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

\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()

2. 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>, \;, ...).

Solution 2 - Python

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDaniel WehnerView Question on Stackoverflow
Solution 1 - PythonJakobView Answer on Stackoverflow
Solution 2 - PythonBonlenfumView Answer on Stackoverflow