将两个 Pyplot 补丁合并为图例

Combine two Pyplot patches for legend

我正在尝试绘制一些带有置信区间的数据。我正在为每个数据流绘制两个图:plotfill_between。我希望图例看起来与绘图相似,其中每个条目都有一个框(置信区域的颜色),中间有一条较暗的实线。到目前为止,我已经能够使用补丁来创建矩形图例键,但我不知道如何实现中心线。我尝试使用填充,但无法控制位置、厚度或颜色。

我最初的想法是尝试合并两个补丁(补丁和2DLine);但是,它还没有奏效。有更好的方法吗?我的MWE和现在的数字如下图

import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0,1,11)
y = np.linspace(0,1,11)

plt.plot(x, y, c='r')
plt.fill_between(x, y-0.2, y+0.2, color='r', alpha=0.5)
p = mpatches.Patch(color='r', alpha=0.5, linewidth=0)

plt.legend((p,), ('Entry',))

从您的代码开始,

这是我能找到的离你最近的。可能有一种方法可以按照您想要的方式创建补丁,但我对此也有点陌生,我所能做的就是构建正确的图例:

import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0,1,11)
y = np.linspace(0,1,11)

fig = plt.figure()
ax = fig.add_subplot(111)
plt.plot(x, y, c='r',label='Entry')
plt.fill_between(x, y-0.2, y+0.2, color='r', alpha=0.5)
p_handle = [mpatches.Patch(color='r', alpha=0.5, linewidth=0)]
p_label = [u'Entry Confidence Interval']
handle, label = ax.get_legend_handles_labels()
handles=handle+p_handle
labels=label+p_label
plt.legend(handles,labels,bbox_to_anchor=(0. ,1.02 ,1.,0.3),loc=8,
           ncol=5,mode='expand',borderaxespad=0,prop={'size':9},numpoints=1)

plt.show()

据我所知,您必须创建符合您正在寻找的设计的 ans "artist" 对象,但我找不到实现方法。可以在此线程中找到类似的一些示例: Custom Legend Thread

希望对你有帮助,如果还有更深入的方法,我也很感兴趣。

解决方案是从 CrazyArm 的评论中借用的,可在此处找到:Matplotlib, legend with multiple different markers with one label。显然你可以制作一个句柄列表并只分配一个标签,它神奇地结合了两个 handles/artists.

import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0,1,11)
y = np.linspace(0,1,11)

p1, = plt.plot(x, y, c='r')  # notice the comma!
plt.fill_between(x, y-0.2, y+0.2, color='r', alpha=0.5)
p2 = mpatches.Patch(color='r', alpha=0.5, linewidth=0)

plt.legend(((p1,p2),), ('Entry',))

我有 'similar' 个问题。由于这个问题,我能够实现以下目标。

fig = pylab.figure()
figlegend = pylab.figure(figsize=(3,2))
ax = fig.add_subplot(111)
point1 = ax.scatter(range(3), range(1,4), 250, marker=ur'$\u2640$', label = 'S', edgecolor = 'green')
point2 = ax.scatter(range(3), range(2,5), 250, marker=ur'$\u2640$', label = 'I', edgecolor = 'red')
point3 = ax.scatter(range(1,4), range(3),  250, marker=ur'$\u2642$', label = 'S', edgecolor = 'green')
point4 = ax.scatter(range(2,5), range(3), 250, marker=ur'$\u2642$', label = 'I', edgecolor = 'red')
figlegend.legend(((point1, point3), (point2, point4)), ('S','I'), 'center',  scatterpoints = 1, handlelength = 1)
figlegend.show()
pylab.show()

但是,我的两个(金星和火星)标记在图例中重叠。我试着玩 handlelength,但这似乎没有帮助。任何建议或评论都会有所帮助。