gpt4 book ai didi

python - 使用 matplotlib 中的 pcolor 时出错

转载 作者:太空宇宙 更新时间:2023-11-03 19:05:48 37 4
gpt4 key购买 nike

我是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

请大家帮忙!

最佳答案

我在使用 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 矩阵的行为与 ndarray 完全不同(例如 all(M[0][0][0][0][0] == M[0])True 即使 M.ndim == 2),这里 matplotlib 没有考虑到这一点......你只需要从矩阵创建一个 ndarray:

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

关于python - 使用 matplotlib 中的 pcolor 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14742626/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com