问题描述
对于以下代码
# 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
是常量,则出现以下错误.
with new_SN_map
being a 1D array and mean_SN
and sigma_SN
being constants, I get the following error.
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
此错误的根源是什么?我以为可以进行数值运算.
What is the source of this error? I thought my numerical operations were allowed.
推荐答案
StackOverflow上有一个(有点)相关的问题:
There is a (somewhat) related question on StackOverflow:
这里的问题是形状(nx,ny,1)的数组仍被认为是3D数组,必须被squeeze
d或切成2D数组.
Here the problem was that an array of shape (nx,ny,1) is still considered a 3D array, and must be squeeze
d or sliced into a 2D array.
更一般地说,发生异常的原因
More generally, the reason for the Exception
显示在此处: matplotlib.pyplot.imshow()
需要2D数组,或三维尺寸为3或4的3D阵列!
is shown here: matplotlib.pyplot.imshow()
needs a 2D array, or a 3D array with the third dimension being of shape 3 or 4!
您可以轻松地通过以下方式进行检查(这些检查由imshow
完成,该功能仅是为了在输入无效内容时给出更具体的消息):
You can easily check this with (these checks are done by imshow
, this function is only meant to give a more specific message in case it's not a valid input):
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
),则有必要.
The np.asarray
is what is done internally by matplotlib.pyplot.imshow
so it's generally best you do it too. If you have a numpy array it's obsolete but if not (for example a list
) it's necessary.
在您的特定情况下,您获得了一维数组,因此您需要使用 np.expand_dims()
In your specific case you got a 1D array, so you need to add a dimension with 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
:
or just use something that accepts 1D arrays like plot
:
a = np.array([1,2,3,4,5])
plt.plot(a)
plt.show()
这篇关于TypeError:使用imshow()绘制数组时,图像数据的尺寸无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!