在 Python 3.6.1 中使用带有底图和 contourf 的一些投影时出现 IndexError

IndexError when using some projections with basemap and contourf in Python 3.6.1

我在 Ubuntu 16.4 上使用 Python 3.6.1 64 位,Qt 5.6.2,PyQt5 5.6,底图版本 1.0.7,matplotlib 2.0.2。当我尝试将 contourfbasemap、投影 'cyl' 一起使用时,例如:

from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np

map = Basemap(projection='cyl',lat_0=45,lon_0=-100,resolution='c')

nlats = 73; nlons = 145; delta = 2.*np.pi/(nlons-1)
lats = (0.5*np.pi-delta*np.indices((nlats,nlons))[0,:,:])
lons = (delta*np.indices((nlats,nlons))[1,:,:])
wave = 0.75*(np.sin(2.*lats)**8*np.cos(4.*lons))
mean = 0.5*np.cos(2.*lats)*((np.sin(2.*lats))**2 + 2.)

x, y = map(lons*180./np.pi, lats*180./np.pi)

cs = map.contour(x,y,wave+mean,15,linewidths=1.5)
plt.show()

我收到以下错误:

Traceback (most recent call last):

File "", line 15, in cs = map.contour(x,y,wave+mean,15,linewidths=1.5)

File "/home/gab/anaconda3/lib/python3.6/site-packages/mpl_toolkits/basemap/init.py", line 521, in with_transform return plotfunc(self,x,y,data,*args,**kwargs)

File "/home/gab/anaconda3/lib/python3.6/site-packages/mpl_toolkits/basemap/init.py", line 3542, in contour xx = x[x.shape[0]/2,:]

IndexError: only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices

如果我使用例如投影 'ortho',则不会发生此错误。 运行 这段代码在 Python 2.6 上没有问题。这个问题好像和一样,没有回答

有什么想法吗?

此行为是 python3 整数除法的后续行为。 查找示例:

1) python3:

n=100
print (n/2, (n+1)/2)

输出:50.0 50.5

2) 对于 python 2.7 此代码 returns 50 50

解决方案:

1) 为 python3.

手动更新底图的分割线

你必须为整数 n 编写:n//2 这是应用 python2.

的除法

2) 或 运行 您的程序 python2.

回应 lanadaquenada(我似乎无法评论)

基于 Serenity 的 post,您实际上需要修改底图代码,而不是您的代码。底图很旧,不再真正受支持。它是在 python 2.x 发布时创建的,它似乎使用了 python 2 整数除法。 Python 3 现在做除法 "correctly",但是创建了一些旧代码以利用 python 2 除法。

在使用 python3 和 matplotlib 1.5.3 时,我会收到有关此问题的警告,但这不是致命的。升级到 matplotlib 2.0.2 后,这个错误变得致命,我的谷歌搜索导致你 post。

因此您需要按照 Serenity 的建议 使用

手动换行
xx[x.shape[0]/2, :]

xx[x.shape[0]//2, :] 

对我来说这是 path_where_your_python_libraries_are_installed/site-packages/mpl_toolkits/basemap/__init__.py

中的 3452 和 3644

我使用的是底图版本 1.0.7。

我需要在从 matplotlib 1.5.3 过渡到版本 2.0.2 时进行此更改

这阻止了我的代码崩溃,我对旧版 matplotlib 的基本测试似乎产生了正确的结果。

我希望这不会在其他地方产生意想不到的后果,尽管底图是用旧的整数除法设计的,所以我认为它没问题