2

我是 python 新手。我试图将 matplotlib 中的 pcolor 用于 gridx、gridy 和 V,所有尺寸均为 401x121。功能如下:

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) 

但一直以来,它都会导致以下错误:

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

请帮忙!

4

1 回答 1

1

我在使用 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

numpy 矩阵根本不像 ndarrays (例如all(M[0][0][0][0][0] == M[0])is Trueeven if M.ndim == 2),这里 matplotlib 没有考虑到这一点......你只需要从矩阵创建一个 ndarray :

plt.colormesh(np.array(M)) # no error
于 2014-07-03T08:17:58.860 回答