如何让pyplot中的Hatches在图例中看起来漂亮

1 投票
1 回答
39 浏览
提问于 2025-04-12 21:47

我遇到了一个问题,找不到解决办法,也不知道该怎么问搜索引擎。
我有很多用Python画的图,其中使用了斜线来表示一些不符合条件的部分(所以有些斜线在图中是看不见的)。但是在图例中,这些斜线看起来很奇怪,因为它们没有居中,而是对齐到全局网格。例如,“HS excl.”对应的斜线是“++”,但水平线并没有居中。类似的情况也出现在“STU obs.”和“Vacuum stab.”上。有没有办法调整图例的参考点,或者其他方法来解决这个问题?我的图例代码是这样的:

legend_elements=[Patch(facecolor='none',hatch="\\\\",label='not unitary',edgecolor="#8D8896",lw=1),
                Patch(facecolor='none',hatch="//",label='not bfb',edgecolor="#752692",lw=1),
                Patch(facecolor='none',hatch="---",label='STU obs.',edgecolor="#124C8A",lw=1),
                Patch(facecolor='none',hatch="xx",label='Vacuum stab.',edgecolor="#B9314F",lw=1),
                Patch(facecolor='none',hatch="||",label='HB excl.',edgecolor="#F57200",lw=1),
                Patch(facecolor='none',hatch="++",label='HS excl.',edgecolor="tab:green",lw=1),
                Patch(facecolor='none',hatch="//",label='$h_{95}$ excl.',edgecolor="#4EA5D9",lw=1),
                Patch(facecolor="darkgreen",label='stable')
                ]


ax.legend(handles=legend_elements,ncols=2,loc="lower center",bbox_to_anchor=(0.5, 1.05))

非常感谢。

图例中奇怪的斜线

1 个回答

0

你可以试着把图例的大小调大,比如设置图例的属性为 {'size': 24}。这样一来,图例的标签就会变大,看起来更好:

import matplotlib.pyplot as plt
import numpy as np

# based on the example from https://matplotlib.org/stable/gallery/lines_bars_and_markers/stackplot_demo.html

# data from United Nations World Population Prospects (Revision 2019)
# https://population.un.org/wpp/, license: CC BY 3.0 IGO
year = [1950, 1960, 1970, 1980, 1990, 2000, 2010, 2018]
population = {
    'Asia': [1394, 1686, 2120, 2625, 3202, 3714, 4169, 4560],
    'Europe': [220, 253, 276, 295, 310, 303, 294, 293]
}
hatches = ['+', '.']
colors = ['tab:red', 'tab:blue']

fig, ax = plt.subplots(figsize=(12, 6))
areas = ax.stackplot(year, population.values(), labels=population.keys(), alpha=0.8, colors=colors)
# hatch each area separately
for a, h in zip(areas, hatches):
    a.set_hatch(h)
# show a big legend
ax.legend(loc='upper left', reverse=True, prop={'size': 24})
ax.set_title('Population', fontsize=20)
ax.set_xlabel('Year', fontsize=20)
ax.set_ylabel('Number of people (millions)', fontsize=20)
fig.tight_layout()
plt.show()

效果如下:

这里插入图片描述

为了对比,这就是默认图例大小下同一个图的样子:

这里插入图片描述

撰写回答