Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib animation: interactive zoom/pan with blitting does not work

I found a strange problem with FuncAnimation in matplotlib when using blitting. The following code is a minimal working example which moves a point along a sinusoidal line. The problem ist, that after an interactive zoom/pan operation the axes a redrawn, but the line plot stays on it's original position on screen. It seems that for some reason, a zoom/pan does not trigger a new initialization of the blitting. I am using the Qt5Agg backend with matplotlib 3.0.2 but the problem ist also present with the TkAgg backend. A possible workaround is to make the function update also return the line plot. However, that somehow foils the idea of blitting. Do you know a better fix for this problem?

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.animation

t = np.linspace(0, 10, 100)
y = np.sin(t)

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

line, = ax.plot(t, y)
point, = ax.plot(0, 0, 'o')


def update(i):
    point.set_data([t[i], y[i]])
    return point,


ani = mpl.animation.FuncAnimation(fig, update, frames=t.size, blit=True)
plt.tight_layout()
plt.show()
like image 529
oliver2018 Avatar asked Nov 03 '25 08:11

oliver2018


1 Answers

Thanks to the help of ImportanceOfBeingErnest I found the following solution:

ax.callbacks.connect('xlim_changed', lambda event: ani._blit_cache.clear())
ax.callbacks.connect('ylim_changed', lambda event: ani._blit_cache.clear())

I will try to file a patch for FuncAnimation.

like image 80
oliver2018 Avatar answered Nov 05 '25 21:11

oliver2018



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!