Matplotlib imshow() too many objects for cmap

时光毁灭记忆、已成空白 提交于 2021-02-07 04:22:09

问题


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()

And I get the following error:

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'

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

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?


回答1:


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

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

e.g.

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

or

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

What's happening is that imshow expects

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

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!



来源:https://stackoverflow.com/questions/18478240/matplotlib-imshow-too-many-objects-for-cmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!