我看到的这段代码来自另一个StackOverflow post,它向您展示了如何创建具有多种 colored颜色 的图例条目.我try 稍微修改代码以显示图例中的阴影(//
、xx
等),但无法使其工作.这是我try 添加的舱口.
注:这只是一个最小的例子, idea 是拥有第一个 带阴影的矩形和不带图案的第二个 colored颜色 矩形 或者反之亦然.这个例子应该能帮助我弄清楚如何 (在需要时)将其添加到补丁中.
import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection
# define an object that will be used by the legend
class MulticolorPatch(object):
def __init__(self, colors):
self.colors = colors
# define a handler for the MulticolorPatch object
class MulticolorPatchHandler(object):
def legend_artist(self, legend, orig_handle, fontsize, handlebox):
width, height = handlebox.width, handlebox.height
patches = []
for i, c in enumerate(orig_handle.colors):
patches.append(
plt.Rectangle(
[
width/len(orig_handle.colors) * i - handlebox.xdescent,
-handlebox.ydescent
],
width / len(orig_handle.colors),
height,
facecolor=c,
edgecolor="black",
linewidth=0.5,
hatch='//'
)
)
patch = PatchCollection(patches, match_original=True)
handlebox.add_artist(patch)
return patch
# ------ choose some colors
colors1 = ['r', 'g']
colors2 = ['b', 'y']
# ------ create a dummy-plot (just to show that it works)
f, ax = plt.subplots()
ax.plot([1,2,3,4,5], [1,4.5,2,5.5,3], c='g', lw=0.5, ls='--',
label='... just a line')
ax.scatter(range(len(colors1)), range(len(colors1)), c=colors1)
ax.scatter([range(len(colors2))], [.5]*len(colors2), c=colors2, s=50)
# ------ get the legend-entries that are already attached to the axis
h, l = ax.get_legend_handles_labels()
# ------ append the multicolor legend patches
h.append(MulticolorPatch(colors1))
l.append("a nice multicolor legend patch")
h.append(MulticolorPatch(colors2))
l.append("and another one")
# ------ create the legend
f.legend(h, l, loc='upper left',
handler_map={MulticolorPatch: MulticolorPatchHandler()},
bbox_to_anchor=(.125,.875))
这会产生以下结果,尽管我的目的是创建图案填充:
如何修改此选项以添加图案填充?
提前谢谢!