Best way to animate a contour

Hi,

I’d like to animate the result of plt.contour using a slider to modify the values of the Z array that it takes in. Looking around there doesn’t seem to any sort of set_data method so I’m approaching this by doing:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.widgets import Slider

import mpl_interactions.ipyplot as iplt

fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.25)

delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)

def Z(beep):
    Z1 = beep * np.exp(-X**2 - Y**2)
    Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
    return (Z1 - Z2) * 2
contours = ax.contour(X,Y,Z(0))


def callback(value):
    global contours
    for c in contours.collections:
        c.remove()
    contours = ax.contour(X,Y,Z(value))

slider_ax = plt.axes([0.25, 0.1, 0.65, 0.03])
slider = Slider(slider_ax, label="freq", valmin=0.05, valmax=10)
slider.on_changed(callback)
plt.show()

which seems to work well.

Question

My question is essentially is there something I’m missing here that will come back to bite me? I’m worried by the fact that I’m iterating over artists and that I seem to leave the original collection just hanging around. Is there any better way?

This is also not great because I’m constantly creating and adding new artists, which I’m taken to believe is relatively slow and why we generally prefer to use set_data methods. I’m not sure I’ve ever seen it explicitly stated that adding artists is slow though, is that true?