Matplotlib 3D绘图轴指数位移:如何恢复至正常位置?
修复Matplotlib 3D图坐标轴指数位置偏移问题
我用下方简化代码生成3D图时遇到一个问题:坐标轴的指数被移到了图的下方,没法回到坐标轴附近的常规位置。只有通过plt.show()打开交互式窗口旋转视图时才能看到这些指数,用plt.savefig()导出图片时也无法恢复它们的位置。我试过调整边界框、裁剪设置、格式化器以及缩放比例,都没用。
使用的包版本
matplotlib — 3.7.0 python — 3.10.9 numpy — 1.24.2
绘图代码
# 导入库 import numpy as np import matplotlib.pyplot as plt # 加载数据 rawdata = np.loadtxt("./JUICEPropagationHistory_Q1.dat", delimiter="\t") t, x, y, z = rawdata[:, 0], rawdata[:, 1], rawdata[:, 2], rawdata[:, 3] # 创建画布、坐标轴并绘图 fig = plt.figure() ax1 = fig.add_subplot(1, 1, 1, projection="3d") # 尝试过这种写法也不行:ax1 = fig.add_subplot(projection="3d") traj, = ax1.plot3D(x, y, z,) # 尝试过这种写法也不行:traj, = ax1.plot(x, y, z,) # 显示图像 plt.show()
测试数据子集
以下是10行测试数据(用这个子集也会出现相同问题):
1122009840.0 -48024.55642854782 -1074283.2518446227 -2957002.498288834 -493.87486260547803 1592.593075547164 -578.5977602861286 1122009850.0 -52962.51675637561 -1058340.3559710935 -2962741.5162975215 -493.7145926446957 1595.97762488453 -569.2029174306579 1122009860.0 -57898.79608710603 -1042363.868994681 -2968386.4986451087 -493.5386644229466 1599.3112800269291 -559.7906769165551 1122009870.0 -62833.23787599742 -1026354.3003377155 -2973937.2728212336 -493.3470855897769 1602.5939451510817 -550.3613320588779 1122009880.0 -67765.68565708105 -1010312.1603731712 -2979393.669250775 -493.1398642501385 1605.8255259518153 -540.9151765892451 1122009890.0 -72695.9830477127 -994237.9604094768 -2984755.521297978 -492.91700896390864 1609.0059296436052 -531.4525046479761 1122009900.0 -77623.97375311954 -978132.2126753118 -2990022.6652705 -492.67852874540085 1612.1350649620858 -521.9736107762334 1122009910.0 -82549.50157094198 -961995.4303043876 -2995194.940423384 -492.42443306286776 1615.212842165528 -512.4787899081681 1122009920.0 -87472.41039577057 -945828.1273202132 -3000272.188962945 -492.1547318379962 1618.2391730362876 -502.9683373630679 1122009930.0 -92392.54422367772 -929630.8186208482 -3005254.2560505844 -491.869435445394 1621.2139708822224 -493.4425488375083
问题图示

修复方法
这个问题是Matplotlib 3.7.x版本中3D绘图的坐标轴偏移量计算bug导致的,以下是几种可行的修复方式:
1. 降级Matplotlib版本
将Matplotlib降级到3.6.3版本,该版本不存在此bug:
pip install matplotlib==3.6.3
2. 手动调整指数标签位置
在绘图代码的plt.show()之前添加以下代码,手动修正指数标签的位置:
# 修正所有坐标轴的指数标签位置 for axis in [ax1.xaxis, ax1.yaxis, ax1.zaxis]: axis.offsetText.set_position((0.5, 0))
3. 禁用科学计数法(数据范围允许时)
如果你的数据不需要用科学计数法展示,可以直接关闭:
# 对所有坐标轴禁用科学计数法 ax1.ticklabel_format(style='plain', axis='both')
内容的提问来源于stack exchange,提问作者TransferOrbit
相关产品推荐
相关产品推荐

