You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Matplotlib中为饼图图例的每个颜色方块添加黑色边框

Add Black Borders to Pie Chart Legend Patches (QGIS-Style)

Got it! To add black borders to each color square in your pie chart's legend (matching QGIS's clean legend style), you can iterate over the legend's handle objects and adjust their edge properties. Here's the modified version of your code with this feature:

import numpy as np
import matplotlib.pyplot as plt

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})

# Create the legend as before
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)

# Add black borders to each legend patch
for handle in leg.legendHandles:
    handle.set_edgecolor('black')
    handle.set_linewidth(1)  # Adjust line thickness to your preference

plt.tight_layout()
plt.show()

Quick Breakdown:

  • After creating the legend, we loop through leg.legendHandles—each of these is a Patch object that represents the color square in the legend.
  • set_edgecolor('black') adds the crisp black border, and set_linewidth() lets you tweak how thick the border appears (1 is a good default, but feel free to increase/decrease it).
  • This even works for your white "Snow" category, making its border clearly visible against the background.

内容的提问来源于stack exchange,提问作者tmsppc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 20:12:41