Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LaTeX labels in matplotlib not consistent [duplicate]

I try to use LaTeX labels in matplotlib plots, but they get compiled inconsistently. In the screenshot below you see, that not only the axes' labels, but also not all x- and y-ticks are rendered in LaTeX.

Python plot with latex labels

The MWE for the plot above is given by

#!/usr/bin/python3

import matplotlib.pyplot as plt

fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 0.8, 0.8])

# FONT
plt.rc('text', usetex=True)
plt.rc('font', family='serif')

plt.xlabel(r'$y$', fontsize=18)
plt.ylabel(r'$x$',fontsize=18)

# PLOT
axes.plot([1,2,3], [1,4,9], label=r'$x^2$')

# LEGEND
axes.legend(numpoints=1, loc=1, prop={'size':15})

plt.show()

I tried this on a Debian system and macOS both with TeX Live 2018 installed.

How do I get all labels consistently rendered by LaTeX?

(Note: In the end I want to use Fourier as the math font and ebgaramond as the text font)

like image 882
seyfe Avatar asked Aug 31 '25 01:08

seyfe


1 Answers

I has to do with the order in which you do things. You'll want to specify the rc-parameters before creating the figure:

import matplotlib.pyplot as plt

plt.rc('text', usetex=True)
plt.rc('font', family='serif')

fig, ax = plt.subplots()

ax.set_xlabel(r'$y$', fontsize=18)
ax.set_ylabel(r'$x$', fontsize=18)

ax.plot([1,2,3], [1,4,9], label=r'$x^2$')

ax.legend(numpoints=1, loc=1, prop={'size':15})

plt.show()

This does what you intended:

enter image description here

Notice that I changed the figure creation, as your axis was too small to display the label.

like image 144
Tom de Geus Avatar answered Sep 02 '25 15:09

Tom de Geus