gpt4 book ai didi

python - 使用 matplotlib.ticker 设置 Matplotlib Ytick 标签会产生关键错误

转载 作者:行者123 更新时间:2023-12-01 03:24:39 26 4
gpt4 key购买 nike

我想设置 y-ticker 标签,但仍将它们绑定(bind)到数据。通过这个问题,matplotlib: change yaxis tick labels ,我正在尝试使用 matplotlib.ticker 来做到这一点。

我目前只想要三个位置的刻度线:[.25, .5, .75]。该图正确生成,但通过打印语句,我可以看到它对每个标签迭代两次,以及一些不在我的字典中的其他随机值,从而在这一行生成关键错误: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。 FixFormatter 仅采用字符串序列而不是函数,并发出适当的标签。通过使用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并不是理想的做事方式。您可以通过足够的努力使其工作,但是字典的无序性质使得很难进行简单的不等式检查链,这就是我对这些值进行硬编码的原因。

关于python - 使用 matplotlib.ticker 设置 Matplotlib Ytick 标签会产生关键错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41510336/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com