0

I am trying to do the following: Plot points and store a reference in a dictionary. While animating remove points. A minimal example looks as follows:

%matplotlib qt
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import numpy as np
import matplotlib.animation as animation

fig = plt.figure()  
m = Basemap(projection='aeqd',lat_0=72,lon_0=29, resolution='l',   
        llcrnrlon=15, llcrnrlat=69,
        urcrnrlon=41, urcrnrlat=75.6,area_thresh = 100)

pointDict=dict()

pointDict[1]=m.plot (0, 0,marker='.',label='first')[0]
pointDict[2]=m.plot (0, 0,marker='.',label='second')[0]

def init():
    print ("Init")
    x,y = m(30, 73)
    pointDict[1].set_data(x,y)
    x,y = m(31, 73)
    pointDict[2].set_data(x,y)
    return pointDict.values()

def animate(i):
    print ("Frame {0}".format(i))
    if i==2:
        l=pointDict.pop(1)
        print ("Removing {0}".format(l.get_label()))
        l.remove()
        del l
    return pointDict.values()

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

plt.show()

Output:

Init
Init
Frame 0
Frame 1
Frame 2
Removing first
Frame 3

Interestingly, if I am plotting just the first point (that is, remove pointDict[2]=m.plot and pointDict[2].set_data in the init function), this works. But if both are plotted, neither removing the first, nor the second point works.

Related questions brought me just as far as I am now:

Matplotlib Basemap animation

How to remove lines in a Matplotlib plot

Matplotlib animating multiple lines and text

Python, Matplotlib, plot multi-lines (array) and animation

I am using Anaconda with Python-2.7 kernel.

Community
  • 1
  • 1
MaBra
  • 13
  • 1
  • 4

1 Answers1

0

I found out what the problem is and want therefore to answer my question by myself: The problem with this is somewhat unexpected the blit=True. Obviously, blitting can be only used if the point is set within the animate function. Thus, setting the data in the init routine causes problems. So there are two options: set blit to False, but this is not very elegant. The other option is to set the points in the first frame. Then the init and animate functions that work are as follows:

def init():
    print ("Init")
    pointDict[1].set_data([],[])
    pointDict[2].set_data([],[])
    return pointDict.values()

def animate(i):
    print ("Frame {0}".format(i))
    if i==0:
        print ("Init")
        x,y = m(30, 73)
        pointDict[1].set_data(x,y)
        x,y = m(31, 73)
        pointDict[2].set_data(x,y)

    if i==2:
        l=pointDict.pop(1)
        print ("Removing {0}".format(l.get_label()))
        l.remove()
        del l
    return pointDict.values()

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

plt.show()
MaBra
  • 13
  • 1
  • 4