Search code examples
pythonnumpymatplotlibtex

Can't print a 10 from .format() in superscript in tex in matplotlib


In matplotlib I'm creating a series of graphs using the following code. When I plot it, the calculated superscripts from 1 to 9 render correctly, but in x^10 through x^12, only the 1 is in the superscript, the following digit (0, 1, 2) is on the same line as the x :

fig, axes = plt.subplots(nrows=2, ncols=6, figsize = (14,4.5))

for i, ax in enumerate(axes.flatten()):
    ax.set_title("$x^{}$".format(i+1))
    ax.plot(x,  x**(i+1))
    
fig.tight_layout();

How do I get it to put all the digits in the superscript?


Solution

  • Try replacing the line

        ax.set_title("$x^{}$".format(i+1))
    

    with

        ax.set_title("$x^{{{}}}$".format(i+1))
    

    Matplotlib supports the use of (some) LaTeX expressions in axis titles. In LaTeX, the ^ character causes the next character, or group, to be formatted in superscript. When processing x^10, LaTeX will only set the 1 in superscript, leaving the 0 on the same line as the x, but when processing x^{10} it will set 10 in superscript because 10 is inside the group that the braces { and } surround. (If it didn't do this, how would it know when the superscript ended?)

    When .format encounters {{ and }}, it takes them to mean that you want an actual { or } character in the resulting string, and that they are not part of a placeholder it has to fill with a value. The {} in the middle of "$x^{{{}}}$" is interpreted as the placeholder.

    You end up with three pairs of braces, because it happens that { and } characters have a meaning to both the .format method and to LaTeX.