[英]Adding legend information to matplotlib plot
I have created a confidence interval plot which is working exactly how I want:我创建了一个置信区间图,它完全按照我想要的方式工作:
month = ['Nov-20', 'Dec-20', 'Jan-21', 'Feb-21', 'Mar-21', 'Apr-21', 'May-21', 'Jun-21', 'Jul-21', 'Aug-21', 'Sep-21', 'Oct-21']
x = [0.85704744, 0.74785299, 0.68103776, 0.69793547, 0.8396294 ,
0.25560889, 0.37400785, 0.00742866, 0.84700224, 0.95142221,
0.08544432, 0.09068883]
y = [0.09448781, 0.69683102, 0.96261431, 0.93635227, 0.31503366,
0.38335671, 0.24244469, 0.36712811, 0.22270387, 0.01506295,
0.78433 , 0.38408096]
z = [0.84585527, 0.59615266, 0.60263581, 0.26366399, 0.42948978,
0.18138516, 0.54841131, 0.65201558, 0.03089001, 0.20581638,
0.57586628, 0.33622286]
fig, ax = plt.subplots(figsize=(17,8))
ax.plot(month, z)
ax.fill_between(month, x, y, color='b', alpha=.3)
ax.hlines(y=0.50, xmin=0, xmax=(len(month)), colors='orange', linestyles='--', lw=2, label="Target: 50%")
plt.xlabel('Month')
plt.ylabel('Target %')
plt.rcParams["font.size"] = "20"
plt.ylim((0.1, 1.0))
plt.legend(bbox_to_anchor=(1.04,0.5), loc="center left", borderaxespad=0)
plt.title("Target Forecast Nov20 - Nov21")
plt.show()
plt.close()
However, I want to add the following to the legend:但是,我想在图例中添加以下内容:
fill_between
is the confidence interval蓝色fill_between
是置信区间的指标I did readthis matplotlib documentation , and so I tried:我确实阅读了这个 matplotlib 文档,所以我尝试了:
fig, ax = plt.subplots(figsize=(17,8))
prob, = ax.plot(month, z)
btwn, = ax.fill_between(month, x, y, color='b', alpha=.3)
tgt, = ax.hlines(y=0.50, xmin=0, xmax=(len(month)), colors='orange', linestyles='--', lw=2, label="Target: 50%")
plt.xlabel('Month')
plt.ylabel('Target %')
plt.rcParams["font.size"] = "20"
plt.ylim((0.1, 1.0))
plt.legend([prob, btwn, tgt], ['Probable', 'Confidence Interval', 'Target'])
plt.title("Target Forecast Nov20 - Nov21")
plt.show()
plt.close()
But it ends in a TypeError
:但它以TypeError
结尾:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-61-3ef952c0fc7f> in <module>
1 fig, ax = plt.subplots(figsize=(17,8))
2 prob, = ax.plot(month, z)
----> 3 btwn, = ax.fill_between(month, x, y, color='b', alpha=.3)
4 tgt, = ax.hlines(y=0.50, xmin=0, xmax=(len(month)), colors='orange', linestyles='--', lw=2, label="Target: 50%")
5 plt.xlabel('Month')
TypeError: 'PolyCollection' object is not iterable
How can I add these things to the legend?如何将这些东西添加到图例中?
The matplotlib documentation often suggests to use proxy artists . matplotlib 文档通常建议使用代理艺术家。
Otherwise, in your case, you can just add the label
argument and name it the way you want, and the legend should be updated automatically.否则,在您的情况下,您只需添加label
参数并按照您想要的方式命名,图例就会自动更新。
In your case:在你的情况下:
ax.plot(month, z, label="Probable Forecast")
ax.fill_between(month, x, y, color='b', alpha=.3, label="Confidence Interval")
should work.应该管用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.