gpt4 book ai didi

python - Matplotlib 自定义图例以显示正方形而不是矩形

转载 作者:太空狗 更新时间:2023-10-30 00:59:32 31 4
gpt4 key购买 nike

这是我尝试将条形图的图例从矩形更改为正方形:

import matplotlib.patches as patches

rect1 = patches.Rectangle((0,0),1,1,facecolor='#FF605E')
rect2 = patches.Rectangle((0,0),1,1,facecolor='#64B2DF')
plt.legend((rect1, rect2), ('2016', '2015'))

但是当我绘制这个时,我仍然看到矩形而不是正方形:

enter image description here

关于如何执行此操作有什么建议吗?


我尝试了@ImportanceOfBeingErnest 和@furas 提供的两种解决方案,结果如下:

@ImportanceOfBeingErnest 的解决方案是最容易做到的:

plt.rcParams['legend.handlelength'] = 1
plt.rcParams['legend.handleheight'] = 1.125

结果如下:

enter image description here

我的最终代码如下所示:

plt.legend((df.columns[1], df.columns[0]), handlelength=1, handleheight=1) # the df.columns = the legend text

@furas 的解决方案产生了这个,我不知道为什么文本离矩形更远,但我确信可以通过某种方式改变间隙:

enter image description here

最佳答案

Matplotlib 提供了 rcParams

legend.handlelength  : 2.    # the length of the legend lines in fraction of fontsize
legend.handleheight : 0.7 # the height of the legend handle in fraction of fontsize

您可以在对 plt.legend() 的调用中设置那些

plt.legend(handlelength=1, handleheight=1)

或在脚本开头使用 rcParams

import matplotlib
matplotlib.rcParams['legend.handlelength'] = 1
matplotlib.rcParams['legend.handleheight'] = 1

不幸的是,提供相等的 handlelength=1, handleheight=1 不会给出完美的矩形。 handlelength=1, handleheight=1.125 似乎可以完成这项工作,但这可能取决于所使用的字体。


如果您想使用代理艺术家,另一种方法是使用绘图/散点方法中的方形标记。

bar1 = plt.plot([], marker="s", markersize=15, linestyle="", label="2015")

并将其提供给图例,legend(handles=[bar1])。使用这种方法需要设置matplotlib.rcParams['legend.numpoints'] = 1,否则图例中会出现两个标记。


这是两种方法的完整示例

import matplotlib.pyplot as plt
plt.rcParams['legend.handlelength'] = 1
plt.rcParams['legend.handleheight'] = 1.125
plt.rcParams['legend.numpoints'] = 1


fig, ax = plt.subplots(ncols=2, figsize=(5,2.5))

# Method 1: Set the handlesizes already in the rcParams
ax[0].set_title("Setting handlesize")
ax[0].bar([0,2], [6,3], width=0.7, color="#a30e73", label="2015", align="center")
ax[0].bar([1,3], [3,2], width=0.7, color="#0943a8", label="2016", align="center" )
ax[0].legend()

# Method 2: use proxy markers. (Needs legend.numpoints to be 1)
ax[1].set_title("Proxy markers")
ax[1].bar([0,2], [6,3], width=0.7, color="#a30e73", align="center" )
ax[1].bar([1,3], [3,2], width=0.7, color="#0943a8", align="center" )
b1, =ax[1].plot([], marker="s", markersize=15, linestyle="", color="#a30e73", label="2015")
b2, =ax[1].plot([], marker="s", markersize=15, linestyle="", color="#0943a8", label="2016")
ax[1].legend(handles=[b1, b2])

[a.set_xticks([0,1,2,3]) for a in ax]
plt.show()

制作

enter image description here

关于python - Matplotlib 自定义图例以显示正方形而不是矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40672088/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com