2017-06-13 89 views
1

在使用Basemap.contour時發生某些投影時,我遇到了問題。根據給出的例子in the Basemap documentation,我創建了下面的工作代碼,它產生了預期的結果。該示例使用'tmerc'投影。在使用某些投影時使用Basemap.contour()時發生IndexError

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


m2 = Basemap(projection='tmerc', 
       lat_0=0, lon_0=3, 
       llcrnrlon=1.819757266426611, 
       llcrnrlat=41.583851612359275, 
       urcrnrlon=1.841589961763497, 
       urcrnrlat=41.598674173123) 
##m2 = Basemap(projection='kav7',lon_0=0) 

x = np.linspace(0, m2.urcrnrx, 100) 
y = np.linspace(0, m2.urcrnry, 100) 
xx, yy = np.meshgrid(x, y) 
data = np.sin(xx/100)*np.cos(yy/100) 

levels = np.linspace(-1,1,8) 
m2.contour(xx, yy, data, levels) 

plt.show() 

然而,如果切換到在替代方案中m2=Basemap聲明(在示例代碼註釋掉)使用「kav7」投影,代碼失敗,錯誤如下:

Traceback (most recent call last): 
    File "basemap_contour.py", line 20, in <module> 
    m2.contour(xx, yy, data, levels) 
    File "/opt/local/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mpl_toolkits/basemap/__init__.py", line 521, in with_transform 
    return plotfunc(self,x,y,data,*args,**kwargs) 
    File "/opt/local/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/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 

注意當我將lonlat的值「正確」定義時,也會發生這種情況,因此只選擇了儘可能短的示例。有人知道如何解決這個問題嗎?

編輯

在這種情況下是相關的,我使用python版本3.5.3的osx塞拉利昂的機器上。 matplotlib版本是2.0.0,而basemap版本是1.0.7。

+0

我不能重現這個錯誤,而不是調用Basemap.contour,人們可以在BasemapAxes情況下直接調用contour ,用'Basemap(projection ='kav7',lon_0 = 0)'運行代碼'爲我生成[this image](https://i.stack.imgur.com/7vqHr.png)。 – ImportanceOfBeingErnest

+0

@ImportanceOfBeingErnest我明白了。這可能是一個實施問題?我在'osx'上,所有相關的軟件包都與macports一起安裝。 –

+0

我不知道。該錯誤似乎來自底圖內。我有版本1.1.0。 – ImportanceOfBeingErnest

回答

1

我發現了一個非常簡單的解決方法來解決這個問題。

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

fig,ax = plt.subplots() 
m2 = Basemap(projection='kav7',lon_0=0, ax=ax) 

x = np.linspace(0, m2.urcrnrx, 100) 
y = np.linspace(0, m2.urcrnry, 100) 

xx, yy = np.meshgrid(x, y) 
lon,lat = m2(xx,yy, inverse = True) 

data = np.sin(np.pi*lon/180)*np.cos(np.pi*lat/90) 
m2.drawcoastlines(linewidth=0.5) 

levels = np.linspace(-1,1,8) 
##m2.contour(xx, yy, data, levels) 
ax.contour(xx,yy,data,levels) 
plt.show() 

這既產生的Python 2.7和3.6下,下面的圖片:

result of the above code

1

此行爲是根據python3整數除法。尋找例子:

1)python3:

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

輸出:50.0 50.5

2)爲蟒2.7此代碼返回50 50

解決方案:

1)手動更新輪廓以及用於python3的劃分的底圖輪廓函數。

你必須寫整數nn//2這是從python2申請部門。

2)或者用python2運行你的程序。

相關問題