Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combined legend entry for plot and fill_between

This is similar to Matlab: Combine the legends of shaded error and solid line mean, except for Matplotlib. Example code:

import numpy as np
import matplotlib.pyplot as plt

x = np.array([0,1])
y = x + 1
f,a = plt.subplots()
a.fill_between(x,y+0.5,y-0.5,alpha=0.5,color='b')
a.plot(x,y,color='b',label='Stuff',linewidth=3)
a.legend()

plt.show()

The above code produces a legend that looks like this:

enter image description here

How can I create a legend entry that combines the shading from fill_between and the line from plot, so that it looks something like this (mockup made in Gimp):

enter image description here

like image 450
Torbjørn T. Avatar asked Oct 06 '14 13:10

Torbjørn T.


People also ask

How do you add a legend to a subplot?

Create a figure and a set of subplots, using the subplots() method, considering 3 subplots. Plot the curve on all the subplots(3), with different labels, colors. To place the legend for each curve or subplot adding label. To activate label for each curve, use the legend() method.

How do I add another legend in MatPlotLib?

MatPlotLib with PythonPlace the first legend at the upper-right location. Add artist, i.e., first legend on the current axis. Place the second legend on the current axis at the lower-right location. To display the figure, use show() method.

How do I change the order of my legend in MatPlotLib?

Change order of items in the legend The above order of elements in the legend region can be changed by the gca method that uses another sub-method called get_legend_handles_labels method. These handles and labels lists are passed as parameters to legend method with order of indexes.


1 Answers

MPL supports tuple inputs to legend so that you can create composite legend entries (see the last figure on this page). However, as of now PolyCollections--which fill_between creates/returns--are not supported by legend, so simply supplying a PolyCollection as an entry in a tuple to legend won't work (a fix is anticipated for mpl 1.5.x).

Until the fix arrives I would recommend using a proxy artist in conjunction with the 'tuple' legend entry functionality. You could use the mpl.patches.Patch interface (as demonstrated on the proxy artist page) or you could just use fill. e.g.:

import numpy as np
import matplotlib.pyplot as plt

x = np.array([0, 1])
y = x + 1
f, a = plt.subplots()
a.fill_between(x, y + 0.5, y - 0.5, alpha=0.5, color='b')
p1 = a.plot(x, y, color='b', linewidth=3)
p2 = a.fill(np.NaN, np.NaN, 'b', alpha=0.5)
a.legend([(p2[0], p1[0]), ], ['Stuff'])

plt.show()

Compound legend with fill_between

like image 174
farenorth Avatar answered Oct 16 '22 11:10

farenorth