matplotlib:将图例键设为正方形

matplotlib: make legend keys square

我正在使用 matplotlib,并希望在制作条形图时将图例中的键更改为正方形而不是矩形。有办法指定吗?

我现在拥有的:

我想要的:

谢谢!

您可以定义自己的图例键。

我的答案中的条形图是使用 matplotlib barchart demo. (I have removed the error bars). The matplotlib legend guide explains how to define a class to replace legend keys with ellipses. I have modified that class to use squares (by using rectangle patches).

创建的
import numpy as np
from matplotlib.legend_handler import HandlerPatch
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

# Define square (rectangular) patches
# that can be used as legend keys
# (this code is based on the legend guide example)

class HandlerSquare(HandlerPatch):
    def create_artists(self, legend, orig_handle,
                       xdescent, ydescent, width, height, fontsize, trans):
        center = xdescent + 0.5 * (width - height), ydescent
        p = mpatches.Rectangle(xy=center, width=height,
                               height=height, angle=0.0)
        self.update_prop(p, orig_handle, legend)
        p.set_transform(trans)
        return [p]      

# this example is the matplotlib barchart example:

N = 5
menMeans = (20, 35, 30, 35, 27)

ind = np.arange(N)  # the x locations for the groups
width = 0.35       # the width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(ind, menMeans, width, color='r')

womenMeans = (25, 32, 34, 20, 25)
rects2 = ax.bar(ind+width, womenMeans, width, color='y')

# add some text for labels, title and axes ticks
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(ind+width)
ax.set_xticklabels( ('G1', 'G2', 'G3', 'G4', 'G5') )

# append the new patches to the legend-call:

ax.legend( (rects1[0], rects2[0]), ('Men', 'Women'), 
           handler_map={rects1[0]: HandlerSquare(), rects2[0]: HandlerSquare()})

plt.show()

定义 class HandlerSquare 后,现在可以将其作为 ax.legend 调用的第三个参数应用于每个图例条目。注意语法:

handler_map={rects1[0]: HandlerSquare(), rects2[0]: HandlerSquare()}

handler_map 必须是字典。

这会给你这个情节:

如果你想要一个非常快速和肮脏的解决方案来获得一个近似的正方形(这可能需要根据你的情节进行一些微调),你可以在图例调用中调整 handlelength kwarg。按照 Schorsch 的解决方案(即,一旦您拥有矩形图例艺术家和相应标签的列表):

ax.legend((rects1[0], rects2[0]), ('Men', 'Women'), handlelength=0.7)

有关详细信息,请参阅 matplotlib legend() docs

全局修改handlelength会影响图例中其他标记的宽度。因此,该解决方案将与例如不兼容。点和线补丁的组合。相反,您可以使用 Line2D 向图例添加一个方点标记。您只需将其关联的行设置为零宽度:

rect1 = mlines.Line2D([], [], marker="s", markersize=30, linewidth=0, color="r")
rect2 = mlines.Line2D([], [], marker="s", markersize=30, linewidth=0, color="y")
ax.legend((rect1, rect2), ('Men', 'Women'))