Numpy pcolormesh: TypeError:C的维度与X和/或Y不兼容

18 投票
1 回答
32419 浏览
提问于 2025-04-18 13:36

这段代码:

xedges = np.arange(self.min_spread - 0.5, self.max_spread + 1.5)
yedges = np.arange(self.min_span - 0.5, self.max_span + 1.5)
h, xe, ye = np.histogram2d(
    self.spread_values
    , self.span_values
    , [xedges, yedges]
)
fig = plt.figure(figsize=(7,3))
ax = fig.add_subplot(111)
x, y = np.meshgrid(xedges, yedges)
ax.pcolormesh(x, y, h)

出现了这个错误:

TypeError: Dimensions of C (55, 31) are incompatible with X (56) and/or Y (32); see help(pcolormesh)

如果有55x31个箱子,那么在网格中,56x32的箱子边缘不是正确的吗?

1 个回答

40

这看起来可能很神奇,但其实解释起来很简单……

错误信息是这样打印出来的:

if not (numCols in (Nx, Nx - 1) and numRows in (Ny, Ny - 1)):
    raise TypeError('Dimensions of C %s are incompatible with'
                            ' X (%d) and/or Y (%d); see help(%s)' % (
                                C.shape, Nx, Ny, funcname))

这里的重点是,C的形状是以(行,列)的顺序打印的,而X代表的是列,Y代表的是行。你需要有一个形状为(31, 55)的数组才能让它正常工作。

把你的数组转置一下,问题就解决了。确实,这个错误信息让人有点意外。

撰写回答