发生错误是因为 plt.plot(x, y) 期望 x 和 y 是列表或数组,当您给它一个浮点数时,它有一个长度。您可以通过将[atom1[i]] 括在方括号中使其成为一个列表来避免这种情况。
但是,通常最好避免这种情况,因为目前还不清楚发生了什么。无需循环遍历每个原子,只需将它们全部粘贴到一个数组中,然后绘制数组的列。您甚至可能会发现,当您创建原子时,您可以首先在数组中创建它们。示例:
from matplotlib import pyplot as plt
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
# Define several atoms, these are numpy arrays of length 3
# randomly pulled from a uniform distribution between -1 and 1
atom1 = np.random.uniform(-1, 1, 3)
atom2 = np.random.uniform(-1, 1, 3)
atom3 = np.random.uniform(-1, 1, 3)
atom4 = np.random.uniform(-1, 1, 3)
# Define a list of colors to plot atoms
colors = ['r', 'g', 'b', 'k']
# Here all the atoms are stacked into a (4, 3) array
atoms = np.vstack([atom1, atom2, atom3, atom4])
ax = plt.subplot(111, projection='3d')
# Plot scatter of points
ax.scatter3D(atoms[:, 0], atoms[:, 1], atoms[:, 2], c=colors)
plt.show()
我添加了颜色,因为它有助于查看哪个原子是哪个。