本文介绍了Matplotlib imshow() 用于 cmap 的对象过多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个二维高斯函数的简单imshow()图(matplotlib v.1.2.1):

I'm trying to create a simple imshow() plot (matplotlib v.1.2.1) of a 2D gaussian function:

import matplotlib.pyplot as plt
import numpy as np
from pylab import *

def gaussian(x,y,stdx,stdy):
    return 1.0/(2*np.pi*stdx*stdy) * (np.exp(-0.5*(x**2/stdx**2 + y**2/stdy**2)))

coords = np.linspace(-1,1,100)
X,Y = np.meshgrid(coords,coords)
std_list = np.linspace(1,2,20)
output = [gaussian(X,Y,std_list[i],std_list[i]) for i in range(len(std_list))]

for i in range(len(output)):
    plt.imshow(X,Y,np.array(output[i]),cmap='bone')
    plt.show()

我收到以下错误:

Traceback (most recent call last):
  File "blur.py", line 14, in <module>
    plt.imshow(X,Y,np.array(output[i]),cmap='bone')
TypeError: imshow() got multiple values for keyword argument 'cmap'

事实上,为了确保我没有疯,我完全去掉了 cmap 参数,现在我收到以下错误:

In fact, to make sure I wasn't crazy, I took out the cmap argument altogether, and now I'm getting the following error:

Traceback (most recent call last):
  File "blur.py", line 14, in <module>
    plt.imshow(X,Y,np.array(output[i]))
  File "/home/username/anaconda/lib/python2.7/site-packages/matplotlib/pyplot.py", line     2737, in imshow
    imlim=imlim, resample=resample, url=url, **kwargs)
  File "/home/username/anaconda/lib/python2.7/site-packages/matplotlib/axes.py", line 7098, in imshow
    if norm is not None: assert(isinstance(norm, mcolors.Normalize))
AssertionError

我已经确保 imshow( ) 的参数都具有相同的形状,所以我不完全确定我做错了什么.这可能是一个错误吗?

I've made sure that the arguments of imshow( ) all have the same shape, so I'm not entirely sure what I'm doing wrong. Could this be a bug?

推荐答案

imshow 不带 x, y, z 作为输入.(不过,pcolorpcolormesh 可以).

imshow doesn't take x, y, z as input. (pcolor and pcolormesh do, however).

要么使用 pcolormesh(x, y, z),要么使用 extent kwarg 来显示.

Either use pcolormesh(x, y, z), or use the extent kwarg to imshow.

例如

plt.imshow(Z, extent=[X.min(), X.max(), Y.min(), Y.max()],
           cmap='bone')

plt.pcolormesh(X, Y, Z, cmap='bone')

发生的事情是 imshow 期望

imshow(X, cmap=None, norm=None, aspect=None, interpolation=None,
         alpha=None, vmin=None, vmax=None, origin=None, extent=None,
         **kwargs)

请注意,第二个参数是 cmap,这解释了为什么在传入额外的 cmap kwarg 时会出现错误.

Notice that the second argument is cmap, which explains why you're getting the error you are when you pass in an additional cmap kwarg.

希望这可以使事情变得简单!祝你好运!

Hopefully that clarifies things a touch! Good luck!

这篇关于Matplotlib imshow() 用于 cmap 的对象过多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 19:51