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

matplotlib如何设置图例Patch仅显示上下边缘、移除左右侧边

实现方案

该需求完全可以实现,核心思路是自定义图例的渲染逻辑,替换默认的完整矩形边框绘制规则,仅保留上下边缘线条。下面是完整可运行的修改后代码:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Patch
from matplotlib.legend_handler import HandlerPatch

# 自定义Patch图例处理器,仅绘制上下边缘
class HandlerFilledArea(HandlerPatch):
    def create_artists(self, legend, orig_handle,
                       xdescent, ydescent, width, height, fontsize, trans):
        # 生成默认填充矩形,保留填充样式
        patch = super().create_artists(legend, orig_handle,
                                       xdescent, ydescent, width, height, fontsize, trans)[0]
        # 关闭默认全边框
        patch.set_edgecolor('none')
        artists = [patch]
        # 添加上边缘横线
        top_line = plt.Line2D([xdescent, xdescent+width], [ydescent+height, ydescent+height],
                              color=orig_handle.get_edgecolor(), lw=orig_handle.get_linewidth())
        # 添加下边缘横线
        bottom_line = plt.Line2D([xdescent, xdescent+width], [ydescent, ydescent],
                                 color=orig_handle.get_edgecolor(), lw=orig_handle.get_linewidth())
        artists.extend([top_line, bottom_line])
        for a in artists:
            a.set_transform(trans)
        return artists

# 原有绘图逻辑不变
x=np.linspace(0,2.,100)
y1=np.power(x,2)*2.+x
y2=np.power(x,2)*2-0.2

plt.plot(x,y1,color="k")
plt.plot(x,y2,color="k")

plt.fill_between(x,y1,y2,facecolor=(0,0,0,0.3),lw=0)

# 图例定义部分,绑定自定义处理器
legend_elements = [Patch(facecolor=(0,0,0,0.4), edgecolor='k', label='Filled area')]
plt.gca().legend(handles=legend_elements, handler_map={Patch: HandlerFilledArea()})

plt.show()

代码逻辑说明:

  • 自定义HandlerFilledArea类继承默认的HandlerPatch,重写图例元素生成方法
  • 保留原Patch的填充效果,关闭默认的全边框绘制
  • 在填充矩形的上下边界位置额外绘制两条横线,和原图的填充区域样式匹配
  • 生成图例时通过handler_map参数绑定自定义处理器即可直接生效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 22:06:04