以下代码
# Numerical operation
SN_map_final = (new_SN_map - mean_SN) / sigma_SN
# Plot figure
fig12 = plt.figure(12)
fig_SN_final = plt.imshow(SN_map_final, interpolation='nearest')
plt.colorbar()
fig12 = plt.savefig(outname12)
new_SN_map
是一维数组且mean_SN
和sigma_SN
是常量,我收到以下错误。
Traceback (most recent call last):
File "c:\Users\Valentin\Desktop\Stage M2\density_map_simple.py", line 546, in <module>
fig_SN_final = plt.imshow(SN_map_final, interpolation='nearest')
File "c:\users\valentin\appdata\local\enthought\canopy\user\lib\site-packages\matplotlib\pyplot.py", line 3022, in imshow
**kwargs)
File "c:\users\valentin\appdata\local\enthought\canopy\user\lib\site-packages\matplotlib\__init__.py", line 1812, in inner
return func(ax, *args, **kwargs)
File "c:\users\valentin\appdata\local\enthought\canopy\user\lib\site-packages\matplotlib\axes\_axes.py", line 4947, in imshow
im.set_data(X)
File "c:\users\valentin\appdata\local\enthought\canopy\user\lib\site-packages\matplotlib\image.py", line 453, in set_data
raise TypeError("Invalid dimensions for image data")
TypeError: Invalid dimensions for image data
此错误的来源是什么?我以为我的数字操作是允许的。
答案 0 :(得分:35)
StackOverflow上有一个(某种程度上)相关的问题:
这里的问题是形状(nx,ny,1)的数组仍然被认为是3D数组,并且必须是squeeze
d或切成2D数组。
更一般地说,异常的原因
TypeError:图像数据的维度无效
显示在这里:matplotlib.pyplot.imshow()
需要2D数组,或者第三维的形状为3或4的3D数组!
您可以轻松地检查(这些检查由imshow
完成,此功能仅用于提供更具体的消息,以防它不是有效输入):
from __future__ import print_function
import numpy as np
def valid_imshow_data(data):
data = np.asarray(data)
if data.ndim == 2:
return True
elif data.ndim == 3:
if 3 <= data.shape[2] <= 4:
return True
else:
print('The "data" has 3 dimensions but the last dimension '
'must have a length of 3 (RGB) or 4 (RGBA), not "{}".'
''.format(data.shape[2]))
return False
else:
print('To visualize an image the data must be 2 dimensional or '
'3 dimensional, not "{}".'
''.format(data.ndim))
return False
在你的情况下:
>>> new_SN_map = np.array([1,2,3])
>>> valid_imshow_data(new_SN_map)
To visualize an image the data must be 2 dimensional or 3 dimensional, not "1".
False
np.asarray
由matplotlib.pyplot.imshow
内部完成,因此通常最好也是这样做。如果你有一个numpy数组它已经过时但如果没有(例如list
)则是必要的。
在您的特定情况下,您有一个1D数组,因此您需要添加np.expand_dims()
import matplotlib.pyplot as plt
a = np.array([1,2,3,4,5])
a = np.expand_dims(a, axis=0) # or axis=1
plt.imshow(a)
plt.show()
或只使用接受一维数组的内容,例如plot
:
a = np.array([1,2,3,4,5])
plt.plot(a)
plt.show()