简体   繁体   中英

How do I format negative power as superscript for the axis label in Python?

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:

在此处输入图像描述

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.

在此处输入图像描述

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))

在此处输入图像描述

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}}}$')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM