简体   繁体   中英

manual legend with matplotlib using mix of plot and fill_between

I am plotting the results of a model fit to data with matplotlib. I plot my model results with a colored line, and I plot the data using fill_between so that the error band is shown. I want my legend to display a gray error band and a gray solid line , even though the curve and band in the figure are plotted in different colors.

I know how to accomplish an independently defined legend using a combination of ax.add_artist and matplotlib.lines , but I do not know how to add an error band using this trick.

import numpy as np 
from matplotlib.pylab import plt
from matplotlib import lines as mlines

x = np.linspace(0, 1, 100)
y = x + 1
ylow, yhigh = 0.9*np.exp(x), 1.1*np.exp(x)

fig, ax = plt.subplots(1, 1)
curve1 = ax.plot(x, y, color='red')
band1 = ax.fill_between(x, ylow, yhigh, color='blue')

solid_line = mlines.Line2D([], [], ls='-', c='gray', label='gray-colored label for line')
band = mlines.Line2D([], [], ls='-', c='gray', label='(incorrect) gray-colored label for band')
first_legend = plt.legend(handles=[solid_line, band], loc=2)
ax.add_artist(first_legend)

Question: how can I get my legend to show a gray band for band1 and a gray line for curve1 ?

图稿

You don't have to plot new lines just for legend. You can (and probably should) use your plot with label. Once you create your legend that way, you can change the color of the legendHandles . I hope this is what you want:

import numpy as np 
from matplotlib.pylab import plt
from matplotlib import lines as mlines

x = np.linspace(0, 1, 100)
y = x + 1
ylow, yhigh = 0.9*np.exp(x), 1.1*np.exp(x)

fig, ax = plt.subplots(1, 1)
curve1 = ax.plot(x, y, color='red', label='gray-colored label for line')
band1 = ax.fill_between(x, ylow, yhigh, color='blue', label='(incorrect) gray-colored label for band')

leg = ax.legend(loc=2)
leg.legendHandles[0].set_color('gray')
leg.legendHandles[1].set_color('gray')
plt.show()

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM