我正在使用matplotlib,并且想要将我的图例中的键更改为正方形而不是矩形,例如,当我制作条形图时.有没有办法指定这个?
我现在拥有的:

我想要的是:

谢谢!
如果你想要一个非常快速和肮脏的解决方案来获得一个近似的平方(可能需要根据你的情节进行一些微调),你可以handlelength在图例调用中调整 kwarg.遵循Schorsch的解决方案(即,一旦有了矩形图例艺术家和相应标签的列表):
ax.legend((rects1[0], rects2[0]), ('Men', 'Women'), handlelength=0.7)
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅matplotlib legend()文档.
您可以定义自己的图例键。
我的答案中的条形图是使用matplotlib barchart demo创建的。(我已经删除了误差线)。matplotlib图例指南解释了如何定义一个类以用省略号替换图例键。我已修改该类以使用正方形(通过使用矩形 patch)。
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()
Run Code Online (Sandbox Code Playgroud)
定义后class HandlerSquare,现在可以将其作为调用的第三个参数应用于每个图例条目ax.legend。注意语法:
handler_map={rects1[0]: HandlerSquare(), rects2[0]: HandlerSquare()}
Run Code Online (Sandbox Code Playgroud)
必须handler_map是字典。
这会给你这个情节:
