我想用matplotlib绘制几个3D点。我的坐标存储在2D数组中,因为我有多个案例,因此我想将所有案例用“for循环”绘制在同一个3D图中,但是当我这样做时,结果出现在不同的图上......
例如:
{{1}}
答案 0 :(得分:1)
每次迭代都会创建一个新图形,并在每次迭代时绘制它。您也总是创建1x1子图网格的第一个suplot。
您可能需要x.shape[0] x 1
网格或1 x x.shape[0]
网格:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
X = np.array([[3,2,1],[4,5,6]])
Y = np.array([[1,2,1],[2,3,4]])
Z = np.array([[10,11,12],[13,12,16]])
# Create figure outside the loop
fig = plt.figure()
for i in range(0,X.shape[0]):
# Add the i+1 subplot of the x.shape[0] x 1 grid
ax = fig.add_subplot(X.shape[0], 1, i+1, projection='3d')
ax.scatter(X[i,:], Y[i,:], Z[i,:], c='r', marker='o')
ax.set_xlabel('Z')
ax.set_ylabel('X')
ax.set_zlabel('Y')
# Show it outside the loop
plt.show()
如果您想将它们全部绘制到相同的地块中,请使用:
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection='3d')
ax.set_xlabel('Z')
ax.set_ylabel('X')
ax.set_zlabel('Y')
for i in range(0,X.shape[0]):
# Only do the scatter inside the loop
ax.scatter(X[i,:], Y[i,:], Z[i,:], c='r', marker='o')
plt.show()