如何在matplotlib图中添加3D子图?
为了在matplotlib图中添加3D子图,我们可以执行以下步骤-
- 设置图形大小并调整子图之间和周围的填充。
- 使用numpy创建x,y和z数据点。
- 创建一个新图形或激活现有图形。
- 使用 projection=’3d’ 将’ax’添加到图形作为subplot安排的一部分。
- 使用 plot() 方法绘制x,y和z数据点。
- 要显示图形,请使用 .show() 方法。
示例
from matplotlib import pyplot as plt
import numpy as np
# Set the figure size
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create x, y and z data points using numpy
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
z = x ** 2 + y ** 2
fig = plt.figure()
# add subplot with projection='3d'
ax = fig.add_subplot(111, projection='3d')
# Plot x, y and z data points
ax.plot(x, y, z, color='red', lw=7)
plt.show()
输出
它将产生以下输出 –