matplotlib动画在更新期间删除线条
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了matplotlib动画在更新期间删除线条相关的知识,希望对你有一定的参考价值。
我创建了一张地图,我正在以纬度和经度坐标的CSV格式读取到Pandas DataFrame中。在DataFrame中读取后,我成功地使用'for'循环绘制了多个大弧。
将一组新坐标添加到CSV时,将绘制一个新的大弧。
但是,一旦删除坐标,我无法弄清楚如何移除大弧。这条线只停留在地图上。
每次更新CSV时,如何删除所有旧行并重新绘制行?我只想查看CS中当前包含的行。
CSV包含以下内容:
sourcelon sourcelat destlon destlat
50.44 30.51 -80.84 35.22
52.52 13.4 -80.84 35.22
43.18 -22.97 -80.84 35.22
44.1 -15.97 -80.84 35.22
55.44 30.51 -80.84 35.22
最小代码如下:
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import matplotlib.animation
# setup mercator map projection.
fig = plt.figure(figsize=(27, 20))
m = Basemap(projection='mill', lon_0=0)
m.drawcoastlines(color='r', linewidth=1.0)
def animate(i):
df = pd.read_csv('c:/python/scripts/test2.csv', sep='s*,s*',header=0, encoding='ascii', engine='python'); df
for x,y,z,w in zip(df['sourcelon'], df['sourcelat'], df['destlon'], df['destlat']):
line, = m.drawgreatcircle(x,y,z,w,color='r')
ani = matplotlib.animation.FuncAnimation(fig, animate, interval=1000)
plt.tight_layout()
plt.show()
答案
Using blitting:
使用blitting时,会自动删除线条。
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import matplotlib.animation
# setup mercator map projection.
fig = plt.figure(figsize=(13, 8))
m = Basemap(projection='mill', lon_0=0)
m.drawcoastlines(color='grey', linewidth=1.0)
def get_data():
a = (np.random.rand(4,2)-0.5)*300
b = (np.random.rand(4,2)-0.5)*150
df= pd.DataFrame(np.concatenate((a,b),axis=1),
columns=['sourcelon','destlon','sourcelat','destlat'])
return df
def animate(i):
df = get_data()
lines = []
for x,y,z,w in zip(df['sourcelon'], df['sourcelat'], df['destlon'], df['destlat']):
line, = m.drawgreatcircle(x,y,z,w,color='r')
lines.append(line)
return lines
ani = matplotlib.animation.FuncAnimation(fig, animate, interval=1000, blit=True)
plt.tight_layout()
plt.show()
Without blitting:
如果不需要blitting,可以手动删除线。
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import matplotlib.animation
# setup mercator map projection.
fig = plt.figure(figsize=(13, 8))
m = Basemap(projection='mill', lon_0=0)
m.drawcoastlines(color='grey', linewidth=1.0)
def get_data():
a = (np.random.rand(4,2)-0.5)*300
b = (np.random.rand(4,2)-0.5)*150
df= pd.DataFrame(np.concatenate((a,b),axis=1),
columns=['sourcelon','destlon','sourcelat','destlat'])
return df
lines = []
def animate(i):
df = get_data()
for line in lines:
line.remove()
del line
lines[:] = []
for x,y,z,w in zip(df['sourcelon'], df['sourcelat'], df['destlon'], df['destlat']):
line, = m.drawgreatcircle(x,y,z,w,color='r')
lines.append(line)
ani = matplotlib.animation.FuncAnimation(fig, animate, interval=1000)
plt.tight_layout()
plt.show()
以上是关于matplotlib动画在更新期间删除线条的主要内容,如果未能解决你的问题,请参考以下文章
Matplotlib 动画图 - 图形在循环完成之前没有响应