【发布时间】:2022-01-10 15:34:46
【问题描述】:
我正在使用 matplotlib,并希望在制作条形图时将图例中的键更改为正方形而不是矩形。有没有办法指定这个?
我现在拥有的:
我想要什么:
谢谢!
【问题讨论】:
标签: python matplotlib
我正在使用 matplotlib,并希望在制作条形图时将图例中的键更改为正方形而不是矩形。有没有办法指定这个?
我现在拥有的:
我想要什么:
谢谢!
【问题讨论】:
标签: python matplotlib
如果您想要一个非常快速且肮脏的解决方案来获得近似正方形(这可能需要根据您的绘图进行一些微调),您可以在图例调用中调整 handlelength kwarg。遵循 Schorsch 的解决方案(即,一旦你有一个矩形图例艺术家和相应标签的列表):
ax.legend((rects1[0], rects2[0]), ('Men', 'Women'), handlelength=0.7)
更多信息请参见matplotlib legend() docs。
【讨论】:
您可以定义自己的图例键。
我的答案中的条形图是使用matplotlib barchart demo 创建的。 (我已经删除了错误栏)。 matplotlib legend guide 解释了如何定义一个类来用省略号替换图例键。我已将该类修改为使用正方形(通过使用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 会影响图例中其他标记的宽度。因此,该解决方案将不兼容,例如点和线补丁的组合。相反,您可以使用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'))
【讨论】: