如何调整Matplotlib 3D散点图右侧边距以显示完整Z轴标签
解决Matplotlib 3D散点图Z轴标签被裁剪的问题
针对你遇到的Z轴标签超出边界的问题,试试下面这几个实用方案:
方案1:调整Z轴标签与轴的间距
通过set_zlabel的labelpad参数增大标签和Z轴的距离,给标签留出足够显示空间:
fig = plt.figure(figsize = (7,7), dpi = 200) ax = fig.add_subplot(projection='3d') xs = df_final_depth['Power'] ys = df_final_depth['Velocity'] z = df_final_depth['Predicted Depth (um)'] zs = df_final_depth['Ground Truth Depth (um)'] ax.scatter(xs, ys, z, s=70, label="Predicted Depth ($\mu$$m$)", marker='o') ax.scatter(xs, ys, zs, label="Ground Truth Depth ($\mu$$m$)", marker='^') ax.set_xlabel("Power ($W$)") ax.set_ylabel("Scanning Velocity ($mm/s$)") # 增大labelpad值,可根据实际显示效果调整 ax.set_zlabel("Depth ($\mu$$m$)", labelpad=20) ax.legend() plt.show()
方案2:手动调整画布边距
用plt.subplots_adjust增大右侧边距,给Z轴标签预留显示空间:
fig = plt.figure(figsize = (7,7), dpi = 200) ax = fig.add_subplot(projection='3d') # 绘图代码与之前一致 ax.set_xlabel("Power ($W$)") ax.set_ylabel("Scanning Velocity ($mm/s$)") ax.set_zlabel("Depth ($\mu$$m$)") ax.legend() # 调整右侧边距,right参数可按需设为0.85或更大 plt.subplots_adjust(right=0.85) plt.show()
方案3:调整3D图视角
通过ax.view_init()修改俯仰角和方位角,让Z轴标签位置更合理,避免被裁剪:
fig = plt.figure(figsize = (7,7), dpi = 200) ax = fig.add_subplot(projection='3d') # 绘图代码与之前一致 ax.set_xlabel("Power ($W$)") ax.set_ylabel("Scanning Velocity ($mm/s$)") ax.set_zlabel("Depth ($\mu$$m$)") ax.legend() # 调整视角,elev为俯仰角,azim为方位角,可按需调整数值 ax.view_init(elev=30, azim=45) plt.show()
方案4:升级Matplotlib版本
如果你的Matplotlib版本较旧,可能存在3D标签布局的bug,升级到最新版本(如>=3.7.0)可能自动解决问题:
pip install --upgrade matplotlib
内容的提问来源于stack exchange,提问作者sina tayebati
相关产品推荐
相关产品推荐

