【问题标题】:How to conditionally format text into tick labels [duplicate]如何有条件地将文本格式化为刻度标签[重复]
【发布时间】:2021-11-05 16:07:33
【问题描述】:

这是我目前使用 matplotlib 制作的图表。有没有办法让 y 轴说“向下 x%”

例如,我希望它说“下降 10%”而不是“-10%”。其余的滴答声也一样。

如果使用 python 而不是 JavaScript,这样的东西可能会有所帮助:Have text displayed instead of numerical values on y axis

【问题讨论】:

标签: python matplotlib


【解决方案1】:

您可以使用FuncFormatter 为刻度定义您喜欢的任何格式。

在这种情况下,您可以使用条件语句将减号更改为 "Down",仅当值小于零时。

import matplotlib.pyplot as plt

x = [0, 5, 10]
y = [0, -25, -50]

fig, ax = plt.subplots()

ax.plot(x, y)

def myformat(x, pos):
    if x >= 0:
        return "{}%".format(x)
    else:
        return "Down {}%".format(-x)

ax.yaxis.set_major_formatter(plt.FuncFormatter(myformat))

plt.tight_layout()
plt.show()

【讨论】:

    猜你喜欢
    • 2019-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-14
    • 2021-09-26
    • 2015-05-23
    • 1970-01-01
    相关资源
    最近更新 更多