首页 > 解决方案 > Matplotlib 底图多形状动画异常:“list”对象没有属性“set_animated”

问题描述

我正在使用底图在地图上绘制一些多边形并制作动画。当我为一个多边形设置动画并更改其形状时,它会起作用。如果我添加第二个,我会遇到异常:

Traceback (most recent call last):
  File "...\Programs\Python\Python37\lib\site-packages\matplotlib\cbook\__init__.py", line 216, in process
    func(*args, **kwargs)
  File "...\Local\Programs\Python\Python37\lib\site-packages\matplotlib\animation.py", line 953, in _start
    self._init_draw()
  File "...\Local\Programs\Python\Python37\lib\site-packages\matplotlib\animation.py", line 1741, in _init_draw
    a.set_animated(self._blit)
AttributeError: 'list' object has no attribute 'set_animated'
Traceback (most recent call last):
  File "...\Local\Programs\Python\Python37\lib\site-packages\matplotlib\cbook\__init__.py", line 216, in process
    func(*args, **kwargs)
  File "...\Local\Programs\Python\Python37\lib\site-packages\matplotlib\animation.py", line 1269, in _handle_resize
    self._init_draw()
  File "..\Local\Programs\Python\Python37\lib\site-packages\matplotlib\animation.py", line 1741, in _init_draw
    a.set_animated(self._blit)
AttributeError: 'list' object has no attribute 'set_animated'

我的代码:

input = pd.read_csv(filename)
data = pd.read_csv(datafilename)


m = Basemap(projection='spstere',boundinglat=-50,lon_0=0,resolution='l', area_thresh = 1000.0)
m.fillcontinents()
m.drawmapboundary()
lon =[]
lat = []
lon1=[]
lat1=[]
for j in range(0,100):
    latlist = list()
    latlist1 = list()
    for i in range(0,361):
        latlist.append(float(input.iloc[j][str(i)]))
        latlist1.append(float(data.iloc[j][str(i)]))
    lat.append(latlist)
    lon.append(list(range(0,361)))
    lat1.append(latlist1)
    lon1.append(list(range(0,361)))
polys = []

x,y = m(lon[0],lat[0])
xy = list(zip(x,y))
poly=Polygon(xy,facecolor='None', alpha=1, edgecolor='green', linewidth=1)

x1,y1 = m(lon1[0],lat1[0])
xy1 = list(zip(x1,y1))
poly1=Polygon(xy1,facecolor='None', alpha=1, edgecolor='red', linewidth=1)

polys.append(poly)
polys.append(poly1)
def init():
    plt.gca().add_patch(polys[0])
    plt.gca().add_patch(polys[1])
    return polys,

def animate(i):
    print(i)
    x,y = m(lon[i], lat[i])
    xy=list(zip(x,y))
    polys[0].set_xy(xy)

    x1,y1 = m(lon1[i], lat1[i])
    xy1=list(zip(x1,y1))
    polys[1].set_xy(xy1)
    return polys,

anim = animation.FuncAnimation(plt.gcf(), animate, init_func=init, frames=100, interval=500, blit=True)

plt.show()

如果我在函数中只返回一个 poly 并设置 blit=False 它可以工作。如果我在函数中只返回一个多边形并且 blit=True - 只有一个多边形发生变化。如何使用 blitting 在一个动画中为两个形状设置动画?

标签: pythonmatplotlibanimationmatplotlib-basemap

解决方案


您需要返回要更新的可迭代艺术家。这通常是一个元组或列表。

polys是艺术家的列表是艺术家
poly, poly1的元组是艺术家
[poly, poly1]的列表是艺术家
(poly, poly1)的元组
等。

但是polys,是一个列表的元组。那个列表不是艺术家,这是错误告诉你的。


推荐阅读