在 matplotlib 中的图例条目周围添加黑色边缘颜色

Adding a black edgecolor around to legend entries in matplotlib

我在 python 中制作了这个饼图,我想知道如何在图例中的每个框颜色周围添加黑框。我的意思是每个颜色方块的周围,例如在 qgis 中。

array = np.array([17.96, 10.74, 12.97,  3.47,  8.52,  3.28,  8.56, 16.79, 17.69,
        0.02])
colors = ['#32560a','#8ba023','#748030','#bcb877', '#ccbb86','#807d51','#d3ee99', '#e5e4e2', '#006fff', '#ffffff']
labels = ['Decidious forest', 'Mesic upland shrub', 'Xeric upland shrub', 'Tundra (non-tussock)','Tundra (tussock)','Prostrate shrub tundra', 'Wetland', 'Bare', 'Water', 'Snow']
fig, ax = plt.subplots(figsize=(10, 8))
ax.pie(array,labels=None,colors=colors, autopct='%0.2f%%', startangle=180, pctdistance=0.85, labeldistance = 1.05,textprops={'fontsize':10})
leg = plt.legend(labels,loc='lower center',bbox_to_anchor=(0.5,-0.05), ncol=5,title='SnowModel Land classes')
leg.get_frame().set_linewidth(0.0)
plt.tight_layout()
handles, labels = ax.get_legend_handles_labels()

一种方法是在 Patch:

的帮助下指定 handles 参数
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Patch

array = np.array([17.96, 10.74, 12.97,  3.47,  8.52,  3.28,  8.56, 16.79, 17.69,0.02])
colors = ['#32560a','#8ba023','#748030','#bcb877', '#ccbb86','#807d51','#d3ee99', '#e5e4e2', '#006fff', '#ffffff']
labels = ['Decidious forest', 'Mesic upland shrub', 'Xeric upland shrub', 'Tundra (non-tussock)','Tundra (tussock)','Prostrate shrub tundra', 'Wetland', 'Bare', 'Water', 'Snow']
outline_handles = [Patch(facecolor=color, edgecolor='black', label=label) for color, label in zip(colors, labels)]

fig, ax = plt.subplots(figsize=(10, 8))
ax.pie(array,labels=None,colors=colors, autopct='%0.2f%%', startangle=180, pctdistance=0.85, labeldistance = 1.05,textprops={'fontsize':10})
leg = plt.legend(handles=outline_handles, loc='lower center',bbox_to_anchor=(0.5,-0.05), ncol=5,title='SnowModel Land classes')
leg.get_frame().set_linewidth(0.0)
plt.tight_layout()
handles, labels = ax.get_legend_handles_labels()

你也可以使用pie函数的wedgeprops

wedgeprops = {"linewidth":1.5, "edgecolor":"black"}
ax.pie(array,labels=None,colors=colors, autopct='%0.2f%%', startangle=180, pctdistance=0.85, labeldistance = 1.05,textprops={'fontsize':10},wedgeprops=wedgeprops)

它还会直接在饼图中添加线。