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

如何旋转包含坐标轴的完整Matplotlib图表以适配倾斜表面展示?

实现Matplotlib图表整体倾斜展示的方案

我用以下代码绘制了一张静压分布图表,功能正常,但因为数据代表倾斜表面的压力,希望将整个图表(含坐标轴)也倾斜展示,匹配目标效果。

原绘图代码

fig1 = plt.figure(figsize=(10, 6))

x_P = PSP_1[:,4]
y_P = PSP_1[:,5]

plt.plot(x_P,y_P, color = "red", label="Static Pressure")

plt.title("Static Pressure")
plt.legend(loc="upper right", frameon=False)
plt.ylabel("[Pa]")
plt.xlabel("[m]")
plt.grid(True)
plt.savefig('STATIC_PRESSURE.jpeg',dpi=100)
plt.show()
plt.close(fig1)

原图表效果

原静压分布图表

目标倾斜效果

目标倾斜展示的图表

解决方案

可以通过Matplotlib的Affine2D旋转变换实现整个图表的倾斜,同时调整标题、标签和刻度的旋转角度保证可读性,修改后的代码如下:

import matplotlib.pyplot as plt
from matplotlib.transforms import Affine2D

fig1 = plt.figure(figsize=(10, 6))
# 创建坐标轴时预留足够边距,避免旋转后内容被裁剪
ax = fig1.add_axes([0.15, 0.15, 0.7, 0.7])

x_P = PSP_1[:,4]
y_P = PSP_1[:,5]

ax.plot(x_P, y_P, color="red", label="Static Pressure")

# 设置倾斜角度(可根据需求调整,示例为30度)
rotate_angle = 30
# 创建旋转变换并应用到坐标轴数据区域
transform = Affine2D().rotate_deg(rotate_angle) + ax.transData
ax.set_transform(transform)

# 反向旋转标题、标签和刻度,保证文字水平可读
ax.set_title("Static Pressure", rotation=-rotate_angle, pad=30)
ax.set_ylabel("[Pa]", rotation=-rotate_angle, labelpad=40)
ax.set_xlabel("[m]", rotation=-rotate_angle, labelpad=40)
ax.tick_params(axis='both', rotation=-rotate_angle)

ax.grid(True)
ax.legend(loc="upper right", frameon=False)

plt.savefig('STATIC_PRESSURE_rotated.jpeg', dpi=100)
plt.show()
plt.close(fig1)

关键说明

  • Affine2D().rotate_deg(rotate_angle)创建指定角度的旋转变换,结合ax.transData将变换应用到整个坐标轴区域
  • 标题、坐标轴标签和刻度需要以反向角度旋转,确保文字保持水平可读
  • 调整pad参数和坐标轴边距(add_axes的参数),避免旋转后内容被画布边缘裁剪

内容的提问来源于stack exchange,提问作者Tiago Azevedo Silva

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 08:22:17