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

时间:2017-05-21 15:04:45

标签: 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 )

结果传奇如下:

enter image description here

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

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

3 个答案:

答案 0 :(得分:7)

试试这个:

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()

输出:

enter image description here

<强>更新

要圆圈,请在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()

新图片:

enter image description here

答案 1 :(得分:5)

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

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

    plt.plot([],[], marker="o", ms=10, ls="")
    
  3. 完整示例:

    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()
    

    (请注意,只有较旧版本的matplotlib才需要mecnumpoints个参数)

    enter image description here

    对于图例中更复杂的形状,您可以使用自定义处理程序地图,请参阅legend guide或以this answer为例

答案 2 :(得分:0)

由于其他答案对我不起作用,我添加了一个超级简单直接的答案:

import matplotlib.pyplot as plt
handles = []
for x in colors:
    handles.append(plt.Line2D([], [], color=x, marker="o", linewidth=0))

您可以调整标记大小以及您想要的任何其他内容(可能是星号等),并且线宽会移除线条,只留下标记。完美运行,超级简单!

更简单:

import matplotlib.pyplot as plt
handles = [(plt.Line2D([], [], color=x, marker="o", linewidth=0)) for x in colors]