gpt4 book ai didi

python - Matplotlib:带有变量的图例条目

转载 作者:行者123 更新时间:2023-12-05 08:36:54 30 4
gpt4 key购买 nike

我是 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()

我错过了什么?

最佳答案

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

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

绘制这个:` enter image description here

关于python - Matplotlib:带有变量的图例条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67330203/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com