2017-03-09 60 views
0

我想用Cartopy創建一個簡單的動畫。基本上只需在地圖上畫幾行即可。到目前爲止,我正在嘗試以下內容:如何做Cartopy簡單動畫

import matplotlib.pyplot as plt 
import cartopy.crs as ccrs 
import matplotlib.animation as animation 
import numpy as np 

ax = plt.axes(projection=ccrs.Robinson()) 
ax.set_global() 
ax.coastlines() 

lons = 10 * np.arange(1, 10) 
lats = 10 * np.arange(1, 10) 

def animate(i): 

    plt.plot([lons[i-1], lons[i]], [lats[i-1], lats[i]], color='blue', transform=ccrs.PlateCarree()) 
    return plt 

anim = animation.FuncAnimation(plt.gcf(), animate, frames=np.arange(1, 8), init_func=None, interval=2000, blit=True) 

plt.show() 

有沒有人知道爲什麼這不起作用?

回答

1

這與cartopy無關,我猜想。問題是你不能從動畫函數返回pyplot。 (這就像而不是購買一本書,你會買下整個書店,然後不知道爲什麼你不能看書店)

最簡單的方法是將阻擊器關閉:

import matplotlib.pyplot as plt 
import matplotlib.animation as animation 
import numpy as np 

fig, ax = plt.subplots() 

lons = 10 * np.arange(1, 10) 
lats = 10 * np.arange(1, 10) 

def animate(i): 
    plt.plot([lons[i-1], lons[i]], [lats[i-1], lats[i]], color='blue') 

anim = animation.FuncAnimation(plt.gcf(), animate, frames=np.arange(1, 8), 
           init_func=None, interval=200, blit=False) 

plt.show() 

如果由於某種原因需要blitting(如果動畫速度太慢或消耗太多CPU,則會出現這種情況),則需要返回要繪製的Line2D對象的列表。

import matplotlib.pyplot as plt 
import matplotlib.animation as animation 
import numpy as np 

fig, ax = plt.subplots() 

lons = 10 * np.arange(1, 10) 
lats = 10 * np.arange(1, 10) 
lines = [] 

def animate(i): 
    line, = plt.plot([lons[i-1], lons[i]], [lats[i-1], lats[i]]) 
    lines.append(line) 
    return lines 

anim = animation.FuncAnimation(plt.gcf(), animate, frames=np.arange(1, 8), 
           interval=200, blit=True, repeat=False) 

plt.xlim(0,100) #<- remove when using cartopy 
plt.ylim(0,100) 
plt.show()