代码之家  ›  专栏  ›  技术社区  ›  Deivid

在折线图中显示轴2中的值标签[重复]

  •  0
  • Deivid  · 技术社区  · 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()
    

    enter image description here

    1 回复  |  直到 1 年前
        1
  •  0
  •   Suraj Shourie    1 年前

    你只需要为添加另一个for循环 y1 以对数据进行注释。我还将 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')
    
    

    输出:

    enter image description here

    推荐文章