我看到的这段代码来自另一个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))

这会产生以下结果,尽管我的目的是创建图案填充:

Plot with MultiColor Legend Entry

如何修改此选项以添加图案填充?

提前谢谢!

推荐答案

目前还不能为集合设置单独的阴影,请参见docs:

但zorder、hatch、ickRadius、capstyle和joinstyle除外 属性,该属性只能为整个集合全局设置.

解决方案是不使用集合:

class MulticolorPatchHandler(object):
    def legend_artist(self, legend, orig_handle, fontsize, handlebox):
        width, height = handlebox.width, handlebox.height
        for i, c in enumerate(orig_handle.colors):
          handlebox.add_artist(
              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='//' if i==0 else None
              )
          )
        return handlebox

以下是使用问题中的样本数据的输出:

Plot with hatches

Python相关问答推荐

使用from_pandas将GeDataFrame转换为polars失败,ArrowType错误:未传递numpy. dype对象

使用GEKKO在简单DTE系统中进行一致初始化

计算相同形状的两个张量的SSE损失

返回nxon矩阵的diag元素,而不使用for循环

三个给定的坐标可以是矩形的点吗

如何访问所有文件,例如环境变量

Pandas - groupby字符串字段并按时间范围 Select

django禁止直接分配到多对多集合的前端.使用user.set()

有没有一种方法可以从python的pussompy比较结果中提取文本?

梯度下降:简化要素集的运行时间比原始要素集长

Stacked bar chart from billrame

如何根据一列的值有条件地 Select 前N个组,然后按两列分组?

如何使用scipy的curve_fit与约束,其中拟合的曲线总是在观测值之下?

Django RawSQL注释字段

可以bcrypts AES—256 GCM加密损坏ZIP文件吗?

为什么if2/if3会提供两种不同的输出?

pysnmp—lextudio使用next()和getCmd()生成器导致TypeError:tuple对象不是迭代器''

循环浏览每个客户记录,以获取他们来自的第一个/最后一个渠道

如何在FastAPI中替换Pydantic的constr,以便在BaseModel之外使用?'

对数据帧进行分组,并按组间等概率抽样n行