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

如何实现带额外轴的Matplotlib子图旋转与面板对齐?

三面板旋转对齐解决方案

直接使用AxesDivider无法适配floating_axes的旋转坐标系,建议为每个子图单独创建FloatingSubplot,通过几何计算调整位置实现对齐。以下是可运行的完整代码:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.transforms import Affine2D
from mpl_toolkits.axisartist import floating_axes

fig = plt.figure(figsize=(8, 8))
plot_extents = 0, 1, 0, 1
# 统一旋转45度(顺时针旋转对应rotate_deg(-45))
transform = Affine2D().rotate_deg(-45)
helper = floating_axes.GridHelperCurveLinear(transform, plot_extents)

# 1. 创建中心contour图的轴
center_ax = floating_axes.FloatingSubplot(fig, 111, grid_helper=helper)
fig.add_subplot(center_ax)
center_aux = center_ax.get_aux_axes(transform)

# 生成示例数据
x1, x2 = np.meshgrid(np.linspace(0,1,50), np.linspace(0,1,50))
y = np.sin(x1*np.pi)*np.cos(x2*np.pi)
center_aux.contourf(x1, x2, y, cmap='viridis')

# 2. 创建右上折线图的轴(对齐中心图的右上边缘)
top_right_helper = floating_axes.GridHelperCurveLinear(transform, plot_extents)
top_right_ax = floating_axes.FloatingSubplot(fig, 111, grid_helper=top_right_helper)
fig.add_subplot(top_right_ax)
# 调整位置:基于中心轴的bbox,向右上方偏移
center_bbox = center_ax.get_position()
# 计算偏移量,根据旋转后的几何关系调整dx和dy
dx = 0.35
dy = 0.35
top_right_ax.set_position([center_bbox.x0 + dx, center_bbox.y0 + dy, 
                           center_bbox.width, center_bbox.height])
top_right_aux = top_right_ax.get_aux_axes(transform)
# 绘制折线图
x_line = np.linspace(0,1,50)
top_right_aux.plot(x_line, np.sin(x_line*2*np.pi), color='red')

# 3. 创建左上折线图的轴(对齐中心图的左上边缘)
top_left_helper = floating_axes.GridHelperCurveLinear(transform, plot_extents)
top_left_ax = floating_axes.FloatingSubplot(fig, 111, grid_helper=top_left_helper)
fig.add_subplot(top_left_ax)
top_left_ax.set_position([center_bbox.x0 - dx, center_bbox.y0 + dy, 
                          center_bbox.width, center_bbox.height])
top_left_aux = top_left_ax.get_aux_axes(transform)
top_left_aux.plot(x_line, np.cos(x_line*2*np.pi), color='blue')

# 隐藏多余的轴元素(可选)
for ax in [top_right_ax, top_left_ax]:
    ax.axis["bottom"].set_visible(False)
    ax.axis["left"].set_visible(False)

plt.show()

关键说明

  • 所有子图共用同一个旋转变换,保证整体旋转角度一致
  • 通过获取中心轴的位置bbox,手动计算并设置其他子图的位置,确保对齐
  • 使用get_aux_axes获取实际用于绘图的轴,所有绘图操作在这个辅助轴上完成

内容的提问来源于stack exchange,提问作者Sven Lämle

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 19:46:08