錯誤發生,因爲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()
我添加了顏色,因爲它有助於查看哪個原子是哪個。
非常感謝您的詳細解答。這是非常有用的,但我也需要知道,如果我可以在原子之間繪製矢量。即,例如,我想繪製從atom1到atom2的矢量。 – user2804070
而不是使用'scatter'只是使用'ax.plot(atoms [:, 0],atoms [:, 1],atoms [:,2])''。這在原子中的每個點之間繪製一條線。您將必須決定如何分割它,例如'atoms [0:1,0]'給出前兩個原子的x座標。 – Greg