简体   繁体   English

如何将负功率格式化为 Python 中轴 label 的上标?

[英]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.我正在编写 function 来格式化 y 轴上的刻度标签。 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.我希望标签为 10^-1、10^-2 等,但功率显示为上标。

This is the function I am using now:这是我现在使用的 function:

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.我试图在 function 中将 x 设为负数,并在大括号中添加减号,但这似乎也不起作用。

在此处输入图像描述

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.您也可以直接传递格式化字符串而不是格式化程序,在这种情况下,将在后台创建一个StrMethodFormatter See set_major_formatter .请参阅set_major_formatter

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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