Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用matplotlib的手动图例,混合使用绘图和填充_Python_Matplotlib - Fatal编程技术网

Python 使用matplotlib的手动图例,混合使用绘图和填充

Python 使用matplotlib的手动图例,混合使用绘图和填充,python,matplotlib,Python,Matplotlib,我正在用matplotlib绘制适合数据的模型结果。我用一条彩色线绘制模型结果,并使用fill\u-between绘制数据,以便显示错误带。我希望图例显示灰色错误带和灰色实线,即使图形中的曲线和带以不同的颜色绘制 我知道如何结合使用ax.add\u artist和matplotlib.lines完成独立定义的图例,但我不知道如何使用此技巧添加错误带 import numpy as np from matplotlib.pylab import plt from matplotlib impor

我正在用matplotlib绘制适合数据的模型结果。我用一条彩色线绘制模型结果,并使用
fill\u-between
绘制数据,以便显示错误带。我希望图例显示灰色错误带和灰色实线,即使图形中的曲线和带以不同的颜色绘制

我知道如何结合使用
ax.add\u artist
matplotlib.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)
问题:如何让图例显示
band1
的灰色带和
curve1
的灰色线


您不必仅为图例绘制新线。您可以(也可能应该)使用带标签的绘图。以这种方式创建图例后,可以更改
legendHandles
的颜色。我希望这就是你想要的:

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()

您不必仅为图例绘制新线。您可以(也可能应该)使用带标签的绘图。以这种方式创建图例后,可以更改
legendHandles
的颜色。我希望这就是你想要的:

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()