Matplotlib如何在图例中正确添加Wedge扇形图元
问题原因
Matplotlib 图例系统默认仅内置了 Line2D、基础矩形 Patch 两类对象的渲染规则:
- 直接传入
Wedge对象时,图例无法匹配对应的渲染逻辑,会回退到默认的线条艺术家渲染模式,因此图例显示为线条而非预期的扇形 - 即便强制使用基础 Patch 处理器,也只会渲染为矩形色块,无法保留 Wedge 本身的扇形形态
解决方案
实现适配 Wedge 的自定义图例处理器,重写渲染方法,让图例项绘制时保留 Wedge 的扇形特征,同时自动适配图例项的显示尺寸。
修正后可运行代码
import matplotlib.pylab as plt from matplotlib.patches import Wedge from matplotlib.legend_handler import HandlerPatch # 定义Wedge专属图例处理器 class HandlerWedge(HandlerPatch): def create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans): # 计算扇形在图例项中的居中坐标 center = (0.5 * width - 0.5 * xdescent, 0.5 * height - 0.5 * ydescent) # 按图例项尺寸自适应计算扇形半径 r = min(width, height) / 2 # 复用原始Wedge的角度、环宽、颜色属性 wedge = Wedge( center, r, orig_handle.theta1, orig_handle.theta2, width=orig_handle.width * r / orig_handle.r, color=orig_handle.get_facecolor() ) self.update_prop(wedge, orig_handle, legend) wedge.set_transform(trans) return [wedge] # 基础样式配置 plt.rcParams['axes.facecolor']='#EEEEEE' plt.rcParams['savefig.facecolor']='#EEEEEE' colors = ['#e41a1c','#377eb8','#4daf4a','#984ea3'] fig1 = plt.figure(figsize=(4, 3)) ax = fig1.gca() radius = 0.5 # 构造图例用的Wedge元素 legend_elements = [ Wedge((0, 1), radius, 0, 90, width=radius, color=colors[0], label='category1'), Wedge((0, 1), radius, 0, 180, width=radius, color=colors[1], label='category2'), Wedge((0, 1), radius, 0, 270, width=radius, color=colors[2], label='category3'), Wedge((0, 1), radius, 0, 360, width=radius, color=colors[3], label='category4') ] # 生成图例时指定Wedge使用自定义处理器 ax.legend( handles=legend_elements, handler_map={Wedge: HandlerWedge()}, loc='lower center', bbox_to_anchor=(0.5, 1.01), ncol=4, borderaxespad=0, frameon=False, handleheight=2 ) fig1.show()
说明
- 自定义处理器会自动同步原始Wedge对象的张角、环宽、填充色、描边等属性,无需重复配置
- 可通过调整
legend参数中的handleheight、handlelength控制图例中扇形的显示大小 - 该方法同样适用于其他自定义Patch子类的图例渲染,只需要对应修改处理器中返回的艺术家对象即可
内容的提问来源于stack exchange,提问作者osprey
相关产品推荐
相关产品推荐

