将 mpatches.Patch 用于自定义图例

新手上路,请多包涵

我正在使用以下代码创建自定义 matplotlib 图例。

 import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
colors = ["g", "w"]
texts = ["Green Data Description", "RedData Description"]
patches = [ mpatches.Patch(color=colors[i], label="{:s}".format(texts[i]) ) for i in range(len(texts)) ]
plt.legend(handles=patches, bbox_to_anchor=(0.5, 0.5), loc='center', ncol=2 )

结果图例如下:

在此处输入图像描述

1 - 图例中的白色符号未显示,因为默认图例背景也是白色。如何将图例背景设置为其他颜色?

2 - 如何将图例中的矩形符号变成圆形?

原文由 Hesham Eraqi 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.7k
2 个回答
  1. 可以使用 facecolor 参数到 plt.legend() 来设置图例的背景颜色,
     plt.legend(facecolor="plum")

  1. 要获得圆形图例句柄,您可以使用带有圆形标记的标准绘图作为代理艺术家,
     plt.plot([],[], marker="o", ms=10, ls="")

完整示例:

 import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
colors = ["g", "w"]
texts = ["Green Data Description", "RedData Description"]
patches = [ plt.plot([],[], marker="o", ms=10, ls="", mec=None, color=colors[i],
            label="{:s}".format(texts[i]) )[0]  for i in range(len(texts)) ]
plt.legend(handles=patches, bbox_to_anchor=(0.5, 0.5),
           loc='center', ncol=2, facecolor="plum", numpoints=1 )

plt.show()

(注意 mecnumpoints 参数仅适用于旧版本的 matplotlib)

在此处输入图像描述

对于图例中更复杂的形状,您可以使用自定义处理程序映射,请参阅 图例指南 或例如 此答案 作为示例

原文由 ImportanceOfBeingErnest 发布,翻译遵循 CC BY-SA 4.0 许可协议

尝试这个:

 import matplotlib.pyplot as plt
import numpy as np
import matplotlib.patches as mpatches
from matplotlib.legend_handler import HandlerPatch
colors = ["g", "w"]
texts = ["Green Data Description", "RedData Description"]
class HandlerEllipse(HandlerPatch):
    def create_artists(self, legend, orig_handle,
                       xdescent, ydescent, width, height, fontsize, trans):
        center = 0.5 * width - 0.5 * xdescent, 0.5 * height - 0.5 * ydescent
        p = mpatches.Ellipse(xy=center, width=width + xdescent,
                             height=height + ydescent)
        self.update_prop(p, orig_handle, legend)
        p.set_transform(trans)
        return [p]

c = [ mpatches.Circle((0.5, 0.5), 1, facecolor=colors[i], linewidth=3) for i in range(len(texts))]
plt.legend(c,texts,bbox_to_anchor=(0.5, 0.5), loc='center', ncol=2, handler_map={mpatches.Circle: HandlerEllipse()}).get_frame().set_facecolor('#00FFCC')
plt.show()

输出:

在此处输入图像描述

更新:

圆形,设置宽度等于高度,在 mpatches.Ellipse

去掉外面的黑线,在 edgecolor="none" mpatches.Circle

代码:

 import matplotlib.pyplot as plt
import numpy as np
import matplotlib.patches as mpatches
from matplotlib.legend_handler import HandlerPatch
colors = ["g", "w"]
texts = ["Green Data Description", "RedData Description"]
class HandlerEllipse(HandlerPatch):
    def create_artists(self, legend, orig_handle,
                       xdescent, ydescent, width, height, fontsize, trans):
        center = 0.5 * width - 0.5 * xdescent, 0.5 * height - 0.5 * ydescent
        p = mpatches.Ellipse(xy=center, width=height + xdescent,
                             height=height + ydescent)
        self.update_prop(p, orig_handle, legend)
        p.set_transform(trans)
        return [p]

c = [ mpatches.Circle((0.5, 0.5), radius = 0.25, facecolor=colors[i], edgecolor="none" ) for i in range(len(texts))]
plt.legend(c,texts,bbox_to_anchor=(0.5, 0.5), loc='center', ncol=2, handler_map={mpatches.Circle: HandlerEllipse()}).get_frame().set_facecolor('#00FFCC')
plt.show()

新图片:

在此处输入图像描述

原文由 Tiny.D 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题