【问题标题】:How to plot a 3D data whose axis are not the same shape?如何绘制轴形状不同的 3D 数据?
【发布时间】:2022-01-12 08:53:13
【问题描述】:

我的数据如下所示:

[
    [1, 2, 3, 4, 5],  #x
    [6, 7, 8, 9, 0],  #y
    [[1, 2, 3], [0, 2, 3], [1, 7, 3], [1, 2, 9], [1, 1, 3]]  #z is 3 values for each one value in x and y
]

如何在 matplotlib 中绘制/可视化此类数据?

我尝试了以下但没有成功:

ax.scatter3D(data[0], data[1], data[2], c=data[2], cmap='Greens');
# and
ax.plot3D(data[0], data[1], data[2], 'gray')

它给了我错误:

# first line ==> ValueError: shape mismatch: objects cannot be broadcast to a single shape
# second line ==> ValueError: input operand has more dimensions than allowed by the axis remapping

【问题讨论】:

    标签: python matplotlib multidimensional-array


    【解决方案1】:

    您需要重塑数据以扩展 xy 以匹配 z

    使用纯python:

    from itertools import product
    a,b,c = zip(*(e for x,y,z in zip(*data) for e in product([x],[y],z)))
    
    import matplotlib.pyplot as plt
    fig = plt.figure()
    ax = fig.add_subplot(projection='3d')
    
    ax.scatter3D(a, b, c, c=c, cmap='Greens');
    

    使用 numpy:

    import numpy as np
    x, y = np.repeat(np.array(data[:2]), 3, axis=1)
    z = data[2]
    
    import matplotlib.pyplot as plt
    fig = plt.figure()
    ax = fig.add_subplot(projection='3d')
    ax.scatter3D(x, y, z, c=z, cmap='Greens')
    

    输出:

    【讨论】:

      猜你喜欢
      • 2023-02-21
      • 2020-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-22
      • 2016-06-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多