Search code examples
pythonmatplotlibtexsubplot

Inconsistent tick labels font with matplotlib subplots


I'm making a grid of plots using matplotlib.pyplot.subplots, and I want the tick labels to be in LaTeX's sans-serif font, but when I do use subplots I always get at least one tick label rendered in matplotlib's default font.

Here's a MWE:

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=1, ncols=1)
x = [1,2,3,4,5]
plt.plot(x)
plt.rc('text', usetex=True)
plt.rc('font', family='sans-serif')
plt.show()

If you comment out the fig, axes = plt.subplots line, the tick labels display as they should.

I'm using python version 3.6.0 and matplotlib version 2.0.0


Solution

  • Changes to the rcParams should always be made as soon as possible and necessarily before the objects they affect are created.

    Thus, putting the rc changes at the top, resolves the issue:

    import matplotlib.pyplot as plt
    plt.rc('text', usetex=True)
    plt.rc('font', family='sans-serif')
    
    fig, axes = plt.subplots(nrows=1, ncols=1)
    x = [1,2,3,4,5]
    plt.plot(x)
    
    plt.show()