简体   繁体   English

使用matplotlib的手动图例,使用plot和fill_between的混合

[英]manual legend with matplotlib using mix of plot and fill_between

I am plotting the results of a model fit to data with matplotlib. 我正在用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. 我用彩色线绘制模型结果,并使用fill_between绘制数据,以显示误差带。 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. 我知道如何使用ax.add_artistmatplotlib.lines的组合来完成独立定义的图例,但是我不知道如何使用此技巧添加错误范围。

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 ? 问:我如何才能让我的传说,以示对灰色带band1和灰线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 . 以这种方式创建图例后,就可以更改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()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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