Combined legend input for plot and fill_between

This is similar to Matlab: Combine legends with a shaded bug and a solid line , with the exception of Matplotlib. Code example:

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 creates a legend that looks like this:

enter image description here

How to create a legend record that combines shading from fill_between and a line from plot , so that it looks something like this (layout made in Gimp):

enter image description here

+5
source share
1 answer

MPL supports legend tuple inputs so you can create compound legend entries (see the last digit on the page on this page ). However, at the moment, PolyCollections - which fill_between create / return - are not supported by the legend, so just providing PolyCollection as an entry in the tuple to the legend will not work (a fix is ​​expected for mpl 1.5.x ).

Until a fix arrives, I would recommend using a proxy artist in conjunction with the recording functionality of the 'tuple' legend. You can use the mpl.patches.Patch interface (as shown on the proxy executor page), or you can just use the fill. eg:.

 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

+7
source

Source: https://habr.com/ru/post/1204107/


All Articles