matplotlib blitting (animated plot) can't resize figure

Viewed 105

I have an animated line using the example given on the matplotlib site:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2 * np.pi, 100)

fig, ax = plt.subplots()

(ln,) = ax.plot(x, np.sin(x), animated=True)

plt.show(block=False)
plt.pause(0.1)

bg = fig.canvas.copy_from_bbox(fig.bbox)

ax.draw_artist(ln)

fig.canvas.blit(fig.bbox)

for j in range(100):
    fig.canvas.restore_region(bg)
    ln.set_ydata(np.sin(x + (j / 100) * np.pi))
    ax.draw_artist(ln)
    fig.canvas.blit(fig.bbox)
    fig.canvas.flush_events()

This yields the plot:

regular figure

When I resize the window of the figure, it no longer works as intended:

resized figure

What is the problem here?

1 Answers

I am having the same issue. This seems to happen as you save the bitmap of the background the first frame and avoid redrawing it. I found that this can be solved by checking for resizes and updating the background to the new one. Your example fixed bellow:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2 * np.pi, 100)

fig, ax = plt.subplots()

(ln,) = ax.plot(x, np.sin(x), animated=True)

plt.show(block=False)
plt.pause(0.1)

bg = fig.canvas.copy_from_bbox(fig.bbox)

ax.draw_artist(ln)

fig.canvas.blit(fig.bbox)
old_fig_size = fig.get_size_inches()

for j in range(100):
    if (old_fig_size != fig.get_size_inches()).any():
        bg = fig.canvas.copy_from_bbox(fig.bbox)   
        old_fig_size = fig.get_size_inches()
    fig.canvas.restore_region(bg)

    ln.set_ydata(np.sin(x + (j / 100) * np.pi))
    ax.draw_artist(ln)
    fig.canvas.blit(fig.bbox)
    fig.canvas.flush_events()
Related