Search code examples
pythoncolorsmatplotlib-animation

change color of new points using animate of matplotlib


I am trying to do an animated plot of a simple sine function where each new point is colored in red and old (meaning: already plotted) dots in gray. I am trying to follow this post since it does what I want with curves. Can someone please tell me what is wrong with my piece of code ?

Here it is:

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


x1 = np.linspace(0,10,1000)
y1 = np.sin(2*np.pi*x1)

fig, ax = plt.subplots()

def init():
    ax.set_xlim([0, 5])
    ax.set_ylim([-2, 2])
    return graph,


graph = None

def animate(i):
    global graph

    if graph is not None:
        graph.set_color('gray')
    graph, = ax.plot(x1[:i+1], y1[:i+1], '*r')
    return graph

ani = animation.FuncAnimation(fig, animate, init_func=init, frames=20, interval=20)

plt.show()

Thank you


Solution

  • I have written a more proper code.

    # Import modules
    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.animation import FuncAnimation
    # ------------------------------------------ #
    
    # Define the data points
    x = np.linspace(0.0, 2.0*np.pi, 80, endpoint=True)
    y = np.sin(x)
    
    # Define the figure and axes of plot
    fig, ax = plt.subplots(figsize=(16,16))
    
    # Define a list that stores temporary data points
    # [[x values], [y values]]
    data_points = [[], []]
    
    # Define the index of the last data point that needs to be plotted
    # For example, if index = 5, data_points[0][-1] = x[5] and data_points[1][-1] = y[5]
    index = 0
    
    # Animation loop
    def animate(i):
         # Global variables
         global data_points, index
    
         # Clear the plot
         ax.clear()
    
         # Append a data point to the list
         data_points[0].append(x[index])
         data_points[1].append(y[index])
    
         # Update the index
         index += 1
    
         # Reset the index and points 
         # if index is out of range
         if (index == len(x)):
              index = 0
              data_points = [[], []]
              
         # Scatter the points
         plt.scatter(x=data_points[0], y=data_points[1], color="grey")
         plt.scatter(x=data_points[0][-1], y=data_points[1][-1], color="red") # Last point is red
    
         # Set the xy limits
         ax.set_xlim(min(x), max(x))
         ax.set_ylim(min(y), max(y))
    
    
    # Calling the animation function
    ani = FuncAnimation(fig, animate, interval=20)
    
    plt.show()
    

    This yields: Animated sine wave

    I hope this helps !