在折线图 matplotlib 中显示轴 2 中的值标签

问题描述 投票:0回答:1

我已经使用 plt.annotate 显示了 y1 标签,但我无法对 y2 执行相同的操作。你能帮我吗?

plt.figure(figsize=(10,4))

x = [201901, 202001, 202101, 202202]
y1 = [6.86, 21.45, 6.25, 0.88]
y2 = [6.33, 6.33, 7.04, 5.63]

plt.box(False)
plt.plot(x, y1, marker='o', label='Your Return')
plt.plot(x, y2, marker='o', label='Benckmark')
plt.legend()
plt.title('Your Return vs Benckmark', pad=30)
plt.xlabel('Period')
plt.ylabel('Return')

for x, y in zip(x, y1):
    label = y
    plt.annotate(label, (x, y),
             xycoords="data",
             textcoords="offset points",
             xytext=(0, 10), ha="center")

plt.show()

python matplotlib label annotate multiple-axes
1个回答
0
投票

您只需为

y1
添加另一个 for 循环来注释数据。我还将
x
重命名为
x_
作为迭代器的名称,否则它将覆盖您的原始变量。

for x_, y in zip(x, y1):
    label = y
    plt.annotate(label, (x_, y),
             xycoords="data",
             textcoords="offset points",
             xytext=(0, 10), ha="center", color ='blue')


for x_, y in zip(x, y2):
    label = y
    plt.annotate(label, (x_, y),
             xycoords="data",
             textcoords="offset points",
             xytext=(0, -10), ha="center", color= 'orange')

输出:

© www.soinside.com 2019 - 2024. All rights reserved.