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

标签 python python-2.7 matplotlib

我想设置 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/

相关文章:

python - BeautifulSoup 选择具有特定类的某些元素中的所有 href

python - 如何在保持所述步骤之间关系的同时将长函数拆分为单独的步骤?

python - 在 Pandas 中分组,同时保留元组

python - 查找字符串是否存在于 Python 的嵌套元组中

python - 绘制按小时和星期几分组的时间序列

python-2.7 - 为什么 Python 线图显示 : Don't have an account? plot.ly

python - Seaborn tsplot 错误

python - 使用字典在Python中将列表拆分为两部分

python - 所有响应都会返回并附加 'None'

python - 与从离散数据插值的曲线相切