Search code examples
pythonmatplotliblatexaxis-labels

Accented Latex letters in Matplotlib label


My question is related to this question.

I want to display for instance $\tilde{b}$ as ylabel in a Matplotlib plot.

MWE

import matplotlib
import matplotlib.pyplot as plt
matplotlib.rc('text', usetex=True)
plt.figure(1)
plt.plot(np.array([0, 1]), np.array([0, 1]))
plt.ylabel('$\tilde{b}$')
plt.show()

The result is that it just shows

ilde b

on the axis. I thought it was related to the fact that b is a consonant, but is does not work either with vowels.

What can I do?


Solution

  • You get that result because in the string you want to render as the label, '$\tilde{b}$', Python recognizes \t as a special character: a horizontal tab.

    It is not the only special character. Another prominent example is \n, which represents a line break. The complete list of special characters can be found in section "String and Bytes literals" of the Python Language Reference.

    Section "Strings" in the Python Tutorial notes:

    If you don’t want characters prefaced by \ to be interpreted as special characters, you can use raw strings by adding an r before the first quote:

    So you get the desired output if instead of

    plt.ylabel('$\tilde{b}$')
    

    you use

    plt.ylabel(r'$\tilde{b}$')
    

    For what it's worth, the line matplotlib.rc('text', usetex=True) in your code (which requires a LaTeX installation in addition to just Matplotlib) is not necessary to reproduce the behavior.