Matplotlib Pyplot并排绘制三线折线图与3D图异常,求解决
问题分析与修正
你的代码核心问题是子图与画布的创建顺序混乱,导致生成了两个独立窗口,3D图根本没画到正确的子图区域:
- 你先调用
plt.subplot(1,2,1)创建了第一个子图占位,但紧接着用fig = plt.figure()新建了一块空白画布(就是那个空的Figure 1),后续所有绘图都跑到了这块新画布上,之前的占位子图直接作废。 - 3D轴的创建方式错误,
ax是坐标轴对象,没有subplot方法,不能强行给它指定子图位置。
修正后的代码
import csv from mpl_toolkits import mplot3d import numpy as np import matplotlib.pyplot as plt # 假设此处已完成x、y、z、idx、type、filename的初始化 # 统一数据类型转换 idx = np.array(idx, dtype=int) x = np.array(x, dtype=float) y = np.array(y, dtype=float) z = np.array(z, dtype=float) # 先创建唯一的画布,再依次添加子图 fig = plt.figure(figsize=(12, 6)) # 指定画布大小,优化并排显示效果 # 第一个子图:3D轨迹图,位置为1行2列的第1个 ax1 = fig.add_subplot(1, 2, 1, projection='3d') ax1.plot3D(x, y, z, 'black') ax1.scatter(x[0], y[0], z[0], c='green', marker='*', s=50) ax1.scatter(x[-1], y[-1], z[-1], c='red', marker='*', s=50) ax1.set_title(type) # 第二个子图:三轴加速度折线图,位置为1行2列的第2个 ax2 = fig.add_subplot(1, 2, 2) ax2.plot(idx, x, label="x") ax2.plot(idx, y, label="y") ax2.plot(idx, z, label="z") ax2.legend(loc="best") ax2.set_title("三轴加速度曲线") # 保存与显示操作均针对同一块画布 plt.savefig(f"{filename}-{type}.png", bbox_inches='tight') plt.show()
关键修正点
- 先创建唯一画布
fig,所有子图都基于该画布生成,避免多窗口问题 - 用
fig.add_subplot()同时指定子图位置和3D投影属性,确保两个图处于同一画布的并排区域 - 避免混用
plt.subplot()与plt.figure()的调用顺序,防止子图与画布脱节
内容的提问来源于stack exchange,提问作者Steve
相关产品推荐
相关产品推荐

