nostradamus
nostradamus

Reputation: 722

Move patch rather than remove it

I have a graph that is gradually revealed. Since this should happen with a huge dataset and on several subplots simultaneously, I was planning to move the patch rather than remove it and draw it from scratch in order to accelerate the code.

My problem is similar to this question. However, I could not resolve it.

Here is a minimal working example:

import numpy as np
import matplotlib.pyplot as plt

nmax = 10
xdata = range(nmax)
ydata = np.random.random(nmax)

fig, ax = plt.subplots()
ax.plot(xdata, ydata, 'o-')
ax.xaxis.set_ticks(xdata)
plt.ion()

i = 0
while i <= nmax:
    # ------------ Here I would like to move it rather than remove and redraw.
    if i > 0:
        rect.remove()
    rect = plt.Rectangle((i, 0), nmax - i, 1, zorder = 10)
    ax.add_patch(rect)
    # ------------
    plt.pause(0.1)
    i += 1

plt.pause(3)

Upvotes: 2

Views: 1430

Answers (1)

pathoren
pathoren

Reputation: 1666

Maybe this works for you. Instead of removing the patch, you just update its position and its width (with rect.set_x(left_x) and rect.set_width(width)), and then redraw the canvas. Try replacing your loop with this (note that the Rectangle is created once, before the loop):

rect = plt.Rectangle((0, 0), nmax, 1, zorder=10)
ax.add_patch(rect)

for i in range(nmax):
    rect.set_x(i)
    rect.set_width(nmax - i)
    fig.canvas.draw()
    plt.pause(0.1)

Upvotes: 4

Related Questions