【问题标题】:Matplotlib: legend entries with variablesMatplotlib:带有变量的图例条目
【发布时间】:2021-04-30 07:52:34
【问题描述】:

我是 python 的初学者,如果这是一个非常基本的问题,我深表歉意。我希望根据输入变量显示图例条目。我已经在寻找解决方案,但是关于图例的教程似乎都没有涵盖我想要实现的目标。最接近的匹配是this other solution for plt.text,它工作正常,但不适用于图例条目,请参阅下面的代码示例。

from matplotlib import pyplot as plt
import numpy as np

input_var1 = 4
input_var2 = 3

y1 = np.random.rand(10)
y2 = np.random.rand(10)
x = np.linspace(0, 9, 10)

plt.plot(x, y1)
plt.plot(x, y2)

# Neither
plt.legend("Plot with input = {}".format(input_var1))
# nor
plt.legend(f"Plot with input = {input_var1}")
# works

# but this works:
plt.text(2, 0.2, "Some text with variable = {}".format(input_var1))    

plt.show()

我错过了什么?

【问题讨论】:

    标签: python matplotlib legend


    【解决方案1】:

    您需要将一个可迭代对象传递给legend,并且由于您有两个绘图,因此需要传递两个图例条目:

    plt.legend(["First data with {}".format(input_var1),"Second data with {}".format(input_var2)])
    

    绘制这个: `

    【讨论】:

    • 谢谢!是的,为了便于阅读,我用图例输入缩短了我的行,不应该这样做。核心错误是缺少方括号。
    【解决方案2】:

    无需费心创建图例,通过指定绘图的标签就可以支持变量,因此可以通过设置它并调用 plt.legend() 来实现。

    plt.plot(x, y1, label="Plot with input = {}".format(input_var1))
    plt.plot(x, y2, label="Plot with input = {}".format(input_var2))
    
    plt.legend()
    plt.show()
    

    【讨论】:

    • 我没有提到我也尝试过你的方法。在这种情况下,我根本不知道我仍然需要调用 plt.legend()。如果我可以将两个答案都标记为已接受的答案,我会这样做。
    • 我的答案是基本的形式,我会用@jf_的例子来定制它。
    【解决方案3】:

    这也适用于我:

    str1 = 'Plot with input =' + str(input_var1)
    str2 = 'Plot with input =' + str(input_var2)
    plt.legend([str1,str2])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-06
      • 2017-10-07
      • 2012-02-16
      • 1970-01-01
      • 1970-01-01
      • 2018-04-18
      • 1970-01-01
      相关资源
      最近更新 更多