【问题标题】:'Make a 3D scatter plot' ValueError: shape mismatch: objects cannot be broadcast to a single shape'制作 3D 散点图' ValueError:形状不匹配:无法将对象广播到单个形状
【发布时间】:2020-04-28 16:42:29
【问题描述】:

我将使用 matplotlib 绘制 3D 散点图,但我遇到了一些问题。
我有 3 个变量(a:70,b:144,c:3)每个变量的形状不同。
所以,发生值错误。如何制作 3D 散点图?

print(a.shape)
print(b.shape)
print(c.shape)

(70,) (144,) (3,)

# scattering 
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np 

fig = plt.figure(figsize=(10, 5))
ax = fig.add_subplot(111, projection='3d') # Axe3D object

sample_size = 500
x = np.array(a)
y = np.array(b)
z = np.array(c)
ax.scatter(x, y, z, alpha=0.5, cmap=plt.cm.Greens)
plt.title("ax.scatter")
plt.show()

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-58-4590f65025fd> in <module>
     11 y = np.array(ex1_non_split_abn['ptp'])
     12 z = np.array(initial_non_split_abn['ptp'])
---> 13 ax.scatter(x, y, z, alpha=0.5, cmap=plt.cm.Greens)
     14 # plt.savefig('../../assets/images/markdown_img/180612_1225_3dplotting_scattering.svg')
     15 plt.title("ax.scatter")

~\Anaconda3\lib\site-packages\mpl_toolkits\mplot3d\axes3d.py in scatter(self, xs, ys, zs, zdir, s, c, 
depthshade, *args, **kwargs)
   2298 
   2299         xs, ys, zs = np.broadcast_arrays(
-> 2300             *[np.ravel(np.ma.filled(t, np.nan)) for t in [xs, ys, zs]])
   2301         s = np.ma.ravel(s)  # This doesn't have to match x, y in size.
   2302 

~\Anaconda3\lib\site-packages\numpy\lib\stride_tricks.py in broadcast_arrays(*args, **kwargs)
    257     args = [np.array(_m, copy=False, subok=subok) for _m in args]
    258 
--> 259     shape = _broadcast_shape(*args)
    260 
    261     if all(array.shape == shape for array in args):

~\Anaconda3\lib\site-packages\numpy\lib\stride_tricks.py in _broadcast_shape(*args)
    191     # use the old-iterator because np.nditer does not handle size 0 arrays
    192     # consistently
--> 193     b = np.broadcast(*args[:32])
    194     # unfortunately, it cannot handle 32 or more arguments directly
    195     for pos in range(32, len(args), 31):

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

【问题讨论】:

  • 我想展示数据分布的差异。所以,我想制作 3D 散点图并比较数据集。但我只有三个不同数字的数据集。如何比较每个数据集?你对这个问题有什么想法吗?
  • 也许使用三个histograms 或一个stripplot 更合适,两者都可以比较不同一维数组的分布
  • 这是您尝试绘制的偶然图像数据吗?

标签: python matplotlib 3d scatter-plot


【解决方案1】:

您有不同形状的变量。正如我错误理解的那样,您的第三个变量的形状是 3,这可能会导致该错误。你可以试试这个随机增加形状 3 到 32 吗?

【讨论】:

  • 感谢您的回答。但我不能增加数据的形状。因为我可以使用原始数据。 :(
猜你喜欢
  • 2013-06-01
  • 1970-01-01
  • 2021-05-22
  • 2021-02-27
  • 1970-01-01
  • 2021-05-13
  • 2019-02-16
  • 1970-01-01
相关资源
最近更新 更多