[英]How do I format negative power as superscript for the axis label in Python?
我正在編寫 function 來格式化 y 軸上的刻度標簽。 比例是對數的,所以未格式化的軸看起來像這樣:
我希望標簽為 10^-1、10^-2 等,但功率顯示為上標。
這是我現在使用的 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))
但是,這導致減號是上標,而數字是普通字符(見下文)。 我該如何解決? 我試圖在 function 中將 x 設為負數,並在大括號中添加減號,但這似乎也不起作用。
您需要在指數周圍放置雙括號,否則只有第一個字符是上標:
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))
您也可以直接傳遞格式化字符串而不是格式化程序,在這種情況下,將在后台創建一個StrMethodFormatter
。 請參閱set_major_formatter
。
ax.yaxis.set_major_formatter('$10^{{{x:.0f}}}$')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.