Home > database >  Cleaning background in Matplotlib stackplot animation
Cleaning background in Matplotlib stackplot animation

Time:04-26

I have a basic animation with a basic line plot, aka ax.plot(...). I modified it so it produces a stackplot instead of the lineplot (code snippet below).

Problem is the the plot doesn't seem to clean the background with every iteration anymore. You can see this in the top-most brown layer in the images below. Even though the rest of the plot is updating, the original plot never gets erased can still be seen sticking out from the top.

How can I get the background to refresh with every iteration?

enter image description here enter image description here Here is a code snippet:

class Display:
    def __init__(self):
        self.fig, self.ax = plt.subplots()
        self.data = None
        self.lines = []

    def animate(self, i):
        get_data() # This is connected to a random number generator that changes each value a few points at a time

        for index, line in enumerate(self.lines):
            [self.lines[index]] = self.ax.stackplot(range(0, len(self.data[index])), self.data[index])
        return self.lines

    def start(self, data):
        self.data = data

        for index, data in enumerate(self.data):
            self.lines  = self.ax.stackplot(range(len(data)), data)

        ani = animation.FuncAnimation(self.fig, self.animate, interval=5, blit=True)
        plt.show()

CodePudding user response:

I found a workaround. It seems like the very initial state of the plot won't be erased for some types of plot. So you can bypass the issue but starting with a blank plot:

    def start(self, data):
        self.data = data

        for index, data in enumerate(self.data):
            self.lines  = self.ax.stackplot([], [])

        ani = animation.FuncAnimation(self.fig, self.animate, interval=5, blit=True)
        plt.show()
  • Related