如何在 Matplotlib 中绘制 3D 点

How to plot 3D points in Matplotlib

我有一个问题 我有一个包含 1200060 行和 3 列的数据集。列包含点,我必须为其绘制 3D 图。我正在使用下面的代码,但我不知道错误在哪里。

fig = plt.figure()
ax = plt.axes(projection="3d")
count = len(data1.index)
z_line = np.linspace(0, count, 1000)
x_line = np.cos(z_line)
y_line = np.sin(z_line)
ax.plot3D(x_line, y_line, z_line, 'gray')

z_points = count * data1[['z']]
x_points = np.cos(z_points) + 0.1 * data1[['x']]
y_points = np.sin(z_points) + 0.1 * data1[['y']]
ax.scatter3D(x_points, y_points, z_points, c=z_points, cmap='hsv')

plt.show()

错误是:

ValueError: shape mismatch: objects cannot be broadcast to a single shape

我也试过这个但是不成功

fig = plt.figure()
ax = plt.axes(projection="3d")


x = np.linspace(len(data1['z'].index), len(data1['y'].index), len(data1['x'].index))
y = np.linspace(len(data1['z'].index), len(data1['y'].index), len(data1['x'].index))

X = data1[['x']]
Y = data1[['y']]
Z = data1[['z']]

fig = plt.figure()
ax = plt.axes(projection="3d")
ax.plot_wireframe(X, Y, Z, color='green')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')

plt.show()

这个 运行 但没有显示任何输出

并使用与第一个相同的错误

fig = plt.figure()
ax = plt.axes(projection="3d")

num_bars = len(data1.index)
x_pos = data1[['x']], num_bars
y_pos = data1[['y']], num_bars
z_pos = data1[['z']], num_bars
x_size = np.ones(num_bars)
y_size = np.ones(num_bars)
z_size = np.ones(num_bars)

ax.bar3d(x_pos, y_pos, z_pos, x_size, y_size, z_size, color='aqua')
plt.show()

错误:ValueError: shape mismatch: objects cannot be broadcast to a single shape

要么使用 data1['z'] 而不是 data1[['z']],或者您甚至可以使用 data1[['z']].values.

为什么?因为您想在这里使用 Seriesnumpy arrays,而不是 DataFrames.

查看两者的区别:

print(type(data1))
# <class 'pandas.core.frame.DataFrame'>

print(type(data1['x']))
#<class 'pandas.core.series.Series'>

print(type(data1['x'].values))
#<class 'numpy.ndarray'>

print(type(data1[['x']]))
#<class 'pandas.core.frame.DataFrame'>

print(type(data1[['x']].values))
#<class 'numpy.ndarray'>

更准确地说,根本问题是 pandas 不知道应该如何处理两个不同 named 列的添加,因为可以在这里看到:

a = pd.DataFrame({'x':np.arange(0,5)})
b = pd.DataFrame({'y':np.arange(0,5)})
c = pd.DataFrame({'x':np.arange(0,5)})
print(a+b)
### yields:
#        x   y
#    0 NaN NaN
#    1 NaN NaN
#    2 NaN NaN
#    3 NaN NaN
#    4 NaN NaN
print(a+c)
### yields:
#       x
#    0  0
#    1  2
#    2  4
#    3  6
#    4  8