在 Matplotlib 中绘制 3D 立方体、球体和向量
从 plt.figure() 获取 fig,并使用 add_subplot 创建三个不同的轴,其中 projection=3d。
使用 ax.set_title("图形名称") 设置图形标题。使用 ax.quiver 方法绘制向量投影,使用 plot3D 绘制立方体,并在使用正弦和余弦后使用 plot_wireframe 绘制球体。
步骤
创建一个新图形,或激活一个现有图形。
要绘制向量,获取一个二维数组。
获取一个压缩对象。
将一个 ~.axes.Axes 添加到图形中作为子图排列的一部分,具有 3d 投影,其中 nrows = 1,ncols = 3 且索引 = 1。
绘制一个 3D 箭头场。
设置 xlim、ylim 和 zlim。
设置轴的标题(索引为 1)。
将一个 ~.axes.Axes 添加到图形中作为子图排列的一部分,具有 3d 投影,其中 nrows = 1,ncols = 3 且索引 = 2。
使用 plot3D() 创建一个表面图,其中表面和边缘使用绿色传递。
设置轴的标题(索引为 2)。即“立方体”。
将一个 ~.axes.Axes 添加到图形中作为子图排列的一部分,具有 3d 投影,其中 nrows = 1,ncols = 3 且索引 = 3。
要制作球体,将正弦和余弦曲线组合在同一位置。
设置轴的标题(索引为 3),即“球体”。
要显示绘图,请使用 plt.show() 方法。
示例
import matplotlib.pyplot as plt
import numpy as np
from itertools import product, combinations
fig = plt.figure()
# draw vector
soa = np.array([[0, 0, 1, 1, -2, 0], [0, 0, 2, 1, 1, 0],
[0, 0, 3, 2, 1, 0], [0, 0, 4, 0.5, 0.7, 0]])
X, Y, Z, U, V, W = zip(*soa)
ax = fig.add_subplot(131, projection='3d')
ax.quiver(X, Y, Z, U, V, W)
ax.set_xlim([-1, 0.5])
ax.set_ylim([-1, 1.5])
ax.set_zlim([-1, 8])
ax.set_title("Vectors")
# draw cube
ax = fig.add_subplot(132, projection='3d')
r = [-1, 1]
for s, e in combinations(np.array(list(product(r, r, r))), 2):
if np.sum(np.abs(s-e)) == r[1]-r[0]:
ax.plot3D(*zip(s, e), color="green")
ax.set_title("Cube")
# draw sphere
ax = fig.add_subplot(133, projection='3d')
u, v = np.mgrid[0:2*np.pi:20j, 0:np.pi:10j]
x = np.cos(u)*np.sin(v)
y = np.sin(u)*np.sin(v)
z = np.cos(v)
ax.plot_wireframe(x, y, z, color="red")
ax.set_title("Sphere")
plt.show()输出

广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP