Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib imshow() too many objects for cmap

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?

like image 864
astromax Avatar asked Sep 03 '25 09:09

astromax


1 Answers

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!

like image 96
Joe Kington Avatar answered Sep 04 '25 23:09

Joe Kington