matplotlib:更改yaxis刻度标签 [英] matplotlib: change yaxis tick labels
问题描述
对于y轴上的每个刻度标签,我想更改:
label -> 2^label
For each tick label on the y axis, I would like to change:
label -> 2^label
我正在绘制日志日志数据(以2为底),但是我希望标签显示原始数据值.
I am plotting log-log data (base 2), but I would like the labels to show the original data values.
我知道我可以得到当前的y标签
ylabels = plt.getp(plt.gca(), 'yticklabels')
I know I can get the current y labels with
ylabels = plt.getp(plt.gca(), 'yticklabels')
这给了我一个列表:<a list of 9 Text yticklabel objects>
每个都是<matplotlib.text.Text object at 0x...>
This gives me a list: <a list of 9 Text yticklabel objects>
each of which is a <matplotlib.text.Text object at 0x...>
我在 http://matplotlib.org/users/text_props中查看了文本对象的文档. html 但是我仍然不确定更改每个文本标签中的字符串的正确语法是什么.
I looked at the documentation of the text objects at http://matplotlib.org/users/text_props.html but I'm still not sure what the correct syntax is to change the string in each text label.
更改标签后,可以使用以下方法在轴上设置标签:
Once I change the labels, I could set them on the axis using:
plt.setp(plt.gca(), 'yticklabels', ylabels)
推荐答案
如果您想在一般情况下执行此操作,则可以使用FuncFormatter
(请参见:
matplotlib轴标签格式, Matplotlib set_major_formatter AttributeError )
If you want to do this in a general case you can use FuncFormatter
(see :
matplotlib axis label format, imshow: labels as any arbitrary function of the image indices. Matplotlib set_major_formatter AttributeError)
在这种情况下,以下方法应该起作用:
In you case the following should work:
import matplotlib as mpl
import matplotlib.pyplot as plt
def mjrFormatter(x, pos):
return "$2^{{{0}}}$".format(x)
def mjrFormatter_no_TeX(x, pos):
return "2^{0}".format(x)
ax = plt.gca()
ax.yaxis.set_major_formatter(mpl.ticker.FuncFormatter(mjrFormatter))
plt.draw()
逃避的{}
转义是新样式字符串交配的结果
The absured {}
escaping is a consequence of the new-style string frommating
这篇关于matplotlib:更改yaxis刻度标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!