artemis
artemis

Reputation: 7261

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

enter image description here

However, I want to add the following to the legend:

I did read this matplotlib documentation, and so I tried:

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                                 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?

Upvotes: 1

Views: 199

Answers (1)

rjg
rjg

Reputation: 579

The matplotlib documentation often suggests to use proxy artists.

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.

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.

Upvotes: 4

Related Questions