Matplotlib Plot Points Over Time Where Old Points Fade

前端 未结 2 999
青春惊慌失措
青春惊慌失措 2021-01-01 04:53

I would like to achieve two objectives with matplotlib:

  • Dynamically update a scatter plot
  • Slowly make the points that were plotted at previous iterati
2条回答
  •  生来不讨喜
    2021-01-01 05:36

    Just as usual with a scatter plot you may define an array of values and a colormap that maps those values to colors. You can change this array in each iteration to make older points have a different value.

    In the following we take a value of 0 as transparent and a value of 1 as dark blue and create a colormap with those colors.
    In each iteration old values are multiplied by a number smaller than one, new values are set to have a value of 1.

    Running the animation will hence produce fading points.

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.animation
    from matplotlib.colors import LinearSegmentedColormap
    
    fig, ax = plt.subplots()
    ax.set_xlabel('X Axis', size = 12)
    ax.set_ylabel('Y Axis', size = 12)
    ax.axis([0,1,0,1])
    x_vals = []
    y_vals = []
    intensity = []
    iterations = 100
    
    t_vals = np.linspace(0,1, iterations)
    
    colors = [[0,0,1,0],[0,0,1,0.5],[0,0.2,0.4,1]]
    cmap = LinearSegmentedColormap.from_list("", colors)
    scatter = ax.scatter(x_vals,y_vals, c=[], cmap=cmap, vmin=0,vmax=1)
    
    def get_new_vals():
        n = np.random.randint(1,5)
        x = np.random.rand(n)
        y = np.random.rand(n)
        return list(x), list(y)
    
    def update(t):
        global x_vals, y_vals, intensity
        # Get intermediate points
        new_xvals, new_yvals = get_new_vals()
        x_vals.extend(new_xvals)
        y_vals.extend(new_yvals)
    
        # Put new values in your plot
        scatter.set_offsets(np.c_[x_vals,y_vals])
    
        #calculate new color values
        intensity = np.concatenate((np.array(intensity)*0.96, np.ones(len(new_xvals))))
        scatter.set_array(intensity)
    
        # Set title
        ax.set_title('Time: %0.3f' %t)
    
    ani = matplotlib.animation.FuncAnimation(fig, update, frames=t_vals,interval=50)
    
    plt.show()
    

提交回复
热议问题