matplotliblegend

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


Solution

  • 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