【问题标题】:How to plot 3D points in Matplotlib如何在 Matplotlib 中绘制 3D 点
【发布时间】:2021-03-06 21:52:59
【问题描述】:

我有一个问题,我有一个包含 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

【问题讨论】:

    标签: python python-3.x matplotlib 3d


    【解决方案1】:

    使用data1['z'] 代替data1[['z']],或者您甚至可以使用data1[['z']].values

    为什么?因为您想在这里使用 Seriesnumpy 数组,而不是使用 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 不知道它应该如何处理添加两个不同的命名列,如下所示:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-02
      • 1970-01-01
      • 2013-07-19
      • 2013-08-06
      • 2020-12-02
      • 2020-06-12
      • 2016-07-03
      相关资源
      最近更新 更多