Skip to content Skip to sidebar Skip to footer

Matplotlib Animation Removing Lines During Update

I've created a map and I am reading in a CSV of latitude and longitude coordinates into a Pandas DataFrame. I've been successful in plotting multiple great arcs using a 'for' loop

Solution 1:

Using blitting:

When using blitting the lines are automatically removed.

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)

defget_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

defanimate(i):
    df = get_data()
    lines = []
    for x,y,z,w inzip(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:

If blitting is not desired, one may remove the lines manually.

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)

defget_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 = []

defanimate(i):
    df = get_data()
    for line in lines:
        line.remove()
        del line
    lines[:] = []
    for x,y,z,w inzip(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()

Post a Comment for "Matplotlib Animation Removing Lines During Update"