nguyen van linh
nguyen van linh

Reputation: 31

error using pcolor from matplotlib

Im new on python. Im trying to use pcolor from matplotlib for gridx, gridy and V, all size 401x121. Function is as following:

def plotSpatialKM(V,gridx,gridy,step_h):
    plt.figure(figsize=(18,8), dpi=80, facecolor='white')
    plt.pcolor(gridx,gridy,V)
    plt.colorbar()
    plt.xlim(gridx.min(), gridx.max())
    plt.ylim(gridy.min(), gridy.max())
    plt.xlabel('x/h',fontsize=FONTSIZE)
    plt.ylabel('y/h',fontsize=FONTSIZE)
    plt.xticks(fontsize=FONTSIZE)
    plt.yticks(fontsize=FONTSIZE)    
    plt.show()
    return(1) 

But all the time, it causes following error:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1410, in __call__
    return self.func(*args)
  File "C:\Python27\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 276, in resize
    self.show()
  File "C:\Python27\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 348, in draw
    FigureCanvasAgg.draw(self)
  File "C:\Python27\lib\site-packages\matplotlib\backends\backend_agg.py", line 439, in draw
    self.figure.draw(self.renderer)
  File "C:\Python27\lib\site-packages\matplotlib\artist.py", line 54, in draw_wrapper
    draw(artist, renderer, *args, **kwargs)
  File "C:\Python27\lib\site-packages\matplotlib\figure.py", line 999, in draw
    func(*args)
  File "C:\Python27\lib\site-packages\matplotlib\artist.py", line 54, in draw_wrapper
    draw(artist, renderer, *args, **kwargs)
  File "C:\Python27\lib\site-packages\matplotlib\axes.py", line 2086, in draw
    a.draw(renderer)
  File "C:\Python27\lib\site-packages\matplotlib\artist.py", line 54, in draw_wrapper
    draw(artist, renderer, *args, **kwargs)
  File "C:\Python27\lib\site-packages\matplotlib\collections.py", line 755, in draw
    return Collection.draw(self, renderer)
  File "C:\Python27\lib\site-packages\matplotlib\artist.py", line 54, in draw_wrapper
    draw(artist, renderer, *args, **kwargs)
  File "C:\Python27\lib\site-packages\matplotlib\collections.py", line 244, in draw
    self.update_scalarmappable()
  File "C:\Python27\lib\site-packages\matplotlib\collections.py", line 609, in update_scalarmappable
    raise ValueError('Collections can only map rank 1 arrays')
ValueError: Collections can only map rank 1 arrays

Please help out!

Upvotes: 2

Views: 2141

Answers (1)

paugier
paugier

Reputation: 1878

I have encountered the same error using np.matrix.

import matplotlib.pyplot as plt
import numpy as np

A = np.random.random([8, 8])

plt.colormesh(A) # no error
M = np.matrix(A)
plt.colormesh(M) # the same error

The numpy matrices do not act at all like ndarrays (for example all(M[0][0][0][0][0] == M[0]) is True even if M.ndim == 2) and here matplotlib does not take that into account... You just have to create a ndarray from the matrix:

plt.colormesh(np.array(M)) # no error

Upvotes: 1

Related Questions