2017-03-09 63 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()