使用mpatches.Patch获取自定义图例

Hes*_*aqi 5 python matplotlib legend

我正在使用以下代码创建自定义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 )
Run Code Online (Sandbox Code Playgroud)

结果传奇如下:

在此输入图像描述

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

2 - 如何将图例中的矩形符号更改为圆形?

Tin*_*y.D 8

试试这个:

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()
Run Code Online (Sandbox Code Playgroud)

输出:

在此输入图像描述

更新:

要圆,设置宽度等于高度,in 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()
Run Code Online (Sandbox Code Playgroud)

新图片:

在此输入图像描述


Imp*_*est 5

  1. 可以使用的facecolor参数设置图例的背景色plt.legend()

    plt.legend(facecolor="plum")
    
    Run Code Online (Sandbox Code Playgroud)
  2. 要获得圆形图例手柄,您可以使用带有圆形标记的标准绘图作为代理艺术家,

    plt.plot([],[], marker="o", ms=10, ls="")
    
    Run Code Online (Sandbox Code Playgroud)

完整的例子:

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()
Run Code Online (Sandbox Code Playgroud)

(请注意mecnumpoints参数仅对于较旧的matplotlib版本才需要)

在此处输入图片说明

有关图例中更复杂的形状,您可以使用自定义处理程序贴图,请参见图例指南或例如此答案作为示例