'How animation scatter plot with Matplotlib can be done with not superimposed data?

I want to do an animated scatter plot with one only pair of x,y data for each frame.

The code I wrote creates an animated scatter plot but the old dots appear in the plot, that means that new dots are added on the plot, keeping the old ones.

For the code below I want a dot per frame like a moving dot on x axis and not adding one more value.

I tried with plt.clf() but then all data disappear.

%matplotlib notebook
from bokeh.plotting import figure, output_file, show
import pandas
import numpy as np
import matplotlib.animation as animation
from matplotlib.animation import FuncAnimation, PillowWriter
import matplotlib.pyplot as plt

writer = PillowWriter(fps=10)

list_x=[1,2,3,4,5,6,7,8,9]
list_y=[5,5,5,5,5,5,5,5,5]

def plot(listax, listay):
    
    plt.scatter(listax, listay, c='blue', alpha=0.5)

    plt.show()

fig2 = plt.figure()
plt.xlim([0, 10])
plt.ylim([0, 10])
with writer.saving(fig2, "plotvideo.gif", 100):
    for i in range(0, len(list_x)):
        x_value = list_x[i]
        y_value = list_y[i]
        
        writer.grab_frame()
        plot(x_value, y_value)


Solution 1:[1]

Use the .remove() method on the point objects to remove them from the figure.

I would try this:

from bokeh.plotting import figure, output_file, show
import pandas
import numpy as np
import matplotlib.animation as animation
from matplotlib.animation import FuncAnimation, PillowWriter
import matplotlib.pyplot as plt
import time

writer = PillowWriter(fps=10)

list_x=[1,2,3,4,5,6,7,8,9]
list_y=[5,5,5,5,5,5,5,5,5]
points = []

def plot(listax, listay, j):
    
    points.append(plt.scatter(listax[j], listay[j], c='blue', alpha=0.5))
    if len(points) == 2:
        points[0].remove()
        points.pop(0)
    plt.show(block=False)

fig2 = plt.figure()
plt.xlim([0, 10])
plt.ylim([0, 10])
with writer.saving(fig2, "plotvideo.gif", 100):
    for i in range(0, len(list_x)):
        x_value = list_x
        y_value = list_y
        
        writer.grab_frame()
        print(points)
        plot(x_value, y_value, i)

See this link for a better explanation (albeit with a different implementation): How to remove points from a plot?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AustinH1242