Matplotlib: use TeX only if is available

Question:

I would like to run the following snippet:

import matplotlib.pyplot as plt
params = {'text.usetex': True}
plt.rcParams.update(params)

but be able to fall back to 'text.usetex' = False if latex or another requirement (ghostscript comes to mind) is not installed on the machine. What is the most pythonic way to do this?

I was thinking of trying a dummy plot and setting text.usetex to False if an error was raised, but I don’t know which error will be raised if latex is not available.

Asked By: P. Camilleri

||

Answers:

I was looking for the same functionality. After having a look at matplotlib’s code, you have a function:

import matplotlib
usetex = matplotlib.checkdep_usetex(True)

In my case, as LaTeX is not installed, this warning is displayed

usetex mode requires TeX.

And usetex is set to False.

Answered By: Vincent Rouvreau

matplotlib.checkdep_usetex(True) will be depreciated in the Matplotlib 3.6 and in future releases. I recommend using this one-liner solution:

from matplotlib import rcParams
import shutil

rcParams['text.usetex']= True if shutil.which('latex') else False
Answered By: Damodar Rajbhandari
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.