Michael D
Michael D

Reputation: 1747

Using \text in LATEX in Matplotlib

In continuation of the following question:

\text does not work in a matplotlib label and RuntimeError: Failed to process string with tex because latex could not be found

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.xlabel(r"$\frac{\text{Actual Value of Production}}{Demand}$", fontsize=16)

plt.show()

I got the following error:

RuntimeError: Failed to process string with tex because latex could not be found

Which means that the latex should be installed locally.

(Is there any other work around?)

In matplotlib "manual" says, that the following packages needed:

Is there more simple work around to use a \text command in Latex ?

If not what is the most easies way to install above in OSX ?

Upvotes: 3

Views: 7944

Answers (1)

Léonard
Léonard

Reputation: 2630

According to this Matplotlib's documentation section, you can use the restricted TeX that comes with matplotlib without having to install any LaTeX distribution locally:

You can use a subset TeX markup in any matplotlib text string by placing it inside a pair of dollar signs ($).

Note that you do not need to have TeX installed, since Matplotlib ships its own TeX expression parser, layout engine, and fonts.

The error you get comes from the mpl.rcParams['text.usetex'] = True statement which forces Matplotlib to link the TeX interpreter to you local (non-existing) LaTeX distribution. Now I understand that you did it in order to have access to the \text function that does not exist in the native Matplotlib's TeX distribution.

So two solutions:

  • You can use the \mathrm command and enforce space between words with \, (ugly but simple workaround)
from matplotlib import pyplot as plt
import matplotlib as mpl
plt.plot([1, 2, 3])
plt.xlabel(r'$\frac{\mathrm{Actual\,Value\,of\,Production}}\mathrm{{Demand}}$', fontsize=16)

plt.show()
  • If you do not like this solution, then you should install LaTeX locally. On OS X, you can get it from MacTeX.

Upvotes: 5

Related Questions