如何在 Matplotlib 中创建曲面图

Suraj Joshi 2024年2月15日

`Axes3D.plot_surface()` 方法

``````import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d

fig = plt.figure(figsize=(8, 6))
ax3d = plt.axes(projection="3d")

xdata = np.linspace(-3, 3, 100)
ydata = np.linspace(-3, 3, 100)
X, Y = np.meshgrid(xdata, ydata)
Z = 1 / (1 + np.exp(-X - Y))

ax3d = plt.axes(projection="3d")
ax3d.plot_surface(X, Y, Z, cmap="plasma")
ax3d.set_title("Surface Plot in Matplotlib")
ax3d.set_xlabel("X")
ax3d.set_ylabel("Y")
ax3d.set_zlabel("Z")

plt.show()
``````

• `rstride`：行步长，默认值为 10
• `cstride`：列步长，默认值为 10
• `color`：表面的颜色
• `cmap`：表面的颜色图
• `facecolors`：表面中每个补丁的面部颜色
• `norm`：Normalize 的一个实例，用于将值映射到颜色
• `vmin`：要映射的最小值
• `vmax`：要映射的最大值
• `shade`：是否遮罩脸部颜色
``````import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d

fig = plt.figure(figsize=(8, 6))
ax3d = plt.axes(projection="3d")

xdata = np.linspace(-3, 3, 100)
ydata = np.linspace(-3, 3, 100)
X, Y = np.meshgrid(xdata, ydata)
Z = 1 / (1 + np.exp(-X - Y))

ax3d = plt.axes(projection="3d")
surf = ax3d.plot_surface(X, Y, Z, rstride=7, cstride=7, cmap="viridis")
fig.colorbar(surf, ax=ax3d)
ax3d.set_title("Surface Plot in Matplotlib")
ax3d.set_xlabel("X")
ax3d.set_ylabel("Y")
ax3d.set_zlabel("Z")

plt.savefig("Customized Surface Plot.png")

plt.show()
``````

Suraj Joshi is a backend software engineer at Matrice.ai.