Matplotlib:带有变量的图例条目

drd*_*hin 3 python matplotlib legend

我是 python 的初学者,如果这是一个非常基本的问题,我很抱歉。我希望根据输入变量显示图例条目。我已经在寻找解决方案,但关于图例的教程似乎都没有涵盖我想要实现的目标。最接近的匹配是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()
Run Code Online (Sandbox Code Playgroud)

我缺少什么?

jf_*_*jf_ 6

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

plt.legend(["First data with {}".format(input_var1),"Second data with {}".format(input_var2)])
Run Code Online (Sandbox Code Playgroud)

绘制这个:`在此输入图像描述