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

如何在Matplotlib中为分组子图绘制侧边弧形标注括号

完整实现代码

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.path import Path
from matplotlib.patches import PathPatch

fig, axs = plt.subplots(8, 1, figsize=(8,9), sharex=True)
for i, ax in enumerate(axs.flat):
    ax.plot([1,2])
    ax.set_ylabel('Label ' + str(i))
axs[7].set_xlabel('The common x Label')

plt.annotate('Group Label (0,1,2,3)', xy=(.02, 0.7), rotation=90, xycoords='figure fraction',
            horizontalalignment='center', verticalalignment='center', fontsize=14, color='k')
plt.annotate('Group Label (4,5,6,7)', xy=(.02, 0.3), rotation=90, xycoords='figure fraction',
            horizontalalignment='center', verticalalignment='center', fontsize=14, color='k')

# 生成括号原始坐标
npoints = 100
td = np.linspace(np.pi*3/4, np.pi*5/4, npoints)
xd = np.cos(td)
yd = np.sin(td)

# 定义坐标变换参数,适配侧边空白区域
x_scale = 0.068
x_offset = 0.108
# 第一个括号对应0-3子图分组,中心y坐标0.7
y_scale_1 = 0.283
y_offset_1 = 0.7
trans_x1 = xd * x_scale + x_offset
trans_y1 = yd * y_scale_1 + y_offset_1
# 第二个括号对应4-7子图分组,中心y坐标0.3
y_scale_2 = 0.283
y_offset_2 = 0.3
trans_x2 = xd * x_scale + x_offset
trans_y2 = yd * y_scale_2 + y_offset_2

# 构造路径对象
def create_bracket_path(x, y):
    verts = np.column_stack([x, y])
    codes = [Path.MOVETO] + [Path.LINETO]*(len(verts)-1)
    return Path(verts, codes)

path1 = create_bracket_path(trans_x1, trans_y1)
path2 = create_bracket_path(trans_x2, trans_y2)

# 添加括号到画布
patch1 = PathPatch(path1, facecolor='none', edgecolor='red', linewidth=2, transform=fig.transFigure)
patch2 = PathPatch(path2, facecolor='none', edgecolor='red', linewidth=2, transform=fig.transFigure)
fig.patches.extend([patch1, patch2])

plt.show()

核心逻辑说明

  • 直接复用了你已经实现的弧形点生成逻辑,不需要调整原始参数
  • 通过线性缩放和平移把标准弧形映射到侧边空白区域,缩放系数可以根据实际显示效果灵活调整
  • 用Path封装点序列生成路径对象,再通过PathPatch添加到画布,指定transform=fig.transFigure使用全局画布分数坐标,适配跨子图的显示需求
  • 可以通过修改PathPatch的edgecolor、linewidth参数调整括号的样式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 14:18:01