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

如何将2D等高线图与3D曲面图并排绘制展示

实现2D等高线图与3D曲面图并排显示

直接修改代码的布局部分,将两个图放在同一个画布的一行两列子图中即可实现并排效果,修改后的完整代码如下:

import matplotlib.pyplot as plt

# 创建1行2列的画布,设置合适的显示尺寸
fig, (ax1, _) = plt.subplots(1, 2, figsize=(14, 6))

# 绘制2D等高线图
cs = ax1.contour(W, B, contour_cost, levels=50) 
ax1.plot(model_1.w_hist, model_1.b_hist, color='magenta')
ax1.scatter(model_1.w_hist, model_1.b_hist, marker='*', s=40, c='red')
ax1.set_xlabel('w')
ax1.set_ylabel('b')
ax1.set_title('2D 等高线图')

# 绘制3D曲面图,复用第二个子图位置并设置3D投影
ax3d = fig.add_subplot(1, 2, 2, projection='3d')
ax3d.plot_surface(W, B, contour_cost, cmap='plasma')
ax3d.set_xlabel('w')
ax3d.set_ylabel('b')
ax3d.set_zlabel('Cost')
ax3d.set_title('3D 曲面图')

plt.tight_layout()  # 自动调整子图间距,避免标签、标题重叠
plt.show()

关键改动说明:

  • 不再单独创建新画布fig2,而是通过plt.subplots(1, 2)创建包含两个子图的单个画布,确保两张图在同一行排布。
  • 利用fig.add_subplot(1, 2, 2, projection='3d')将第二个子图转换为3D投影轴,实现3D曲面的绘制。
  • 添加plt.tight_layout()自动优化子图间距,避免元素重叠。
  • 可选添加标题区分两张图,提升内容可读性。

内容的提问来源于stack exchange,提问作者Shashwat Gupta

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 18:21:00