![](/img/trans.png)
[英]how to round the yaxis using matplotlib.ticker in python
[英]Setting Matplotlib Ytick labels with matplotlib.ticker yields key error
我想设置y-ticker标签,但仍将它们绑定到数据。 通过这个问题, matplotlib:更改yaxis刻度标签 ,我正在尝试使用matplotlib.ticker
做到这一点。
我目前只想在三个位置上打勾: [.25, .5, .75]
。 该图可以正确生成,但是使用print语句,我可以看到它遍历每个标签两次以及字典中没有的其他一些随机值,从而在此行上生成了关键错误: return label_lookup[x]
。 这些值似乎与每次运行的值都不相同。 是什么导致此问题?
import matplotlib as mpl
import matplotlib.pyplot as plt
label_lookup = {.25: 'Label 1',
.5: 'Label 2',
.75: 'Label 3'}
def mjrFormatter(x, pos):
print x, pos
return label_lookup[x]
ax = plt.gca()
ax.set_yticks([.25,.5,.75], minor=False)
ax.yaxis.set_major_formatter(mpl.ticker.FuncFormatter(mjrFormatter))
plt.draw()
plt.show()
我本人不是matplotlib的专家,但是您似乎想使用FixedFormatter而不是FuncFormatter。 FixedFormatter仅采用一系列字符串而不是函数,并发出适当的标签。 通过使用FixedFormatter,您只需要3个标签,而对于FuncFormatter,则必须具有所有传入的x的有效值。
只需更换
ax.yaxis.set_major_formatter(mpl.ticker.FuncFormatter(mjrFormatter))
同
ax.yaxis.set_major_formatter(mpl.ticker.FixedFormatter(['Label 1', 'Label 2', 'Label 3']))
而没有KeyErrors,您将获得相同的结果。 然后,您也可以摆脱mjrFormatter
,因为您不再使用它。
另外,如果您确实想使用FuncFormatter,则必须能够接受任何x,而不仅仅是精确的0.25、0.5和0.75。 您可以按以下方式重写mjrFormatter
:
def mjrFormatter(x, pos):
print x, pos
if x <= .25:
return 'Label 1'
if x <= .5:
return 'Label 2'
return 'Label 3'
您的字典label_lookup
并不使我成为理想的工作方式。 您可以尽力使它工作,但是字典的无序性质使其很难拥有简单的不等式检查链,这就是为什么我对值进行硬编码的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.