Home > Back-end >  How do I format negative power as superscript for the axis label in Python?
How do I format negative power as superscript for the axis label in Python?

Time:09-02

I am writing a function to format the tick labels on the y axis. The scale is logarithmic, so the unformatted axes looks like this:

enter image description here

I want the labels to be 10^-1, 10^-2, etc. but with the power shown as superscript.

This is the function I am using now:

from matplotlib.ticker import FormatStrFormatter

fmt = lambda x, pos: '$10^{:.0f}$'.format(x, pos)

ax3 = fig.add_subplot()
ax3.yaxis.set_major_formatter(mpl.ticker.FuncFormatter(fmt))

However, this results in the minus being a superscript, but the number a normal character (see below). How do I fix that? I tried to make the x negative in the function and add the minus in the curly brackets but that doesn't seem to work either.

enter image description here

CodePudding user response:

You need to put double braces around the exponent, otherwise only the first character will be superscript:

from matplotlib.ticker import FuncFormatter

fmt = lambda x, pos: f'$10^{{{x:.0f}}}$'

fig, ax = plt.subplots()
ax.set_ylim((-6, -1))
ax.yaxis.set_major_formatter(FuncFormatter(fmt))

enter image description here

You can also directly pass the formatting string instead of a formatter, in which case a StrMethodFormatter will be created under the hood. See set_major_formatter.

ax.yaxis.set_major_formatter('$10^{{{x:.0f}}}$')
  • Related