【发布时间】: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