Python Matplotlib Update Scatter

后端 未结 2 612
独厮守ぢ
独厮守ぢ 2020-12-07 05:20

I tried to write a simple script which updates a scatter plot for every timestep t. I wanted to do it as simple as possible. But all it does is to open a window

相关标签:
2条回答
  • 2020-12-07 05:38

    The simplest, cleanest way to make an animation is to use the matplotlib.animation module.

    Since a scatter plot returns a matplotlib.collections.PathCollection, the way to update it is to call its set_offsets method. You can pass it an array of shape (N, 2) or a list of N 2-tuples -- each 2-tuple being an (x,y) coordinate.

    For example,

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.animation as animation
    
    T = 100
    numbParticles = 2
    particles = np.random.random((T,numbParticles)).tolist()
    x, y = np.array([]), np.array([])
    
    def init():
        pathcol.set_offsets([[], []])
        return [pathcol]
    
    def update(i, pathcol, particles):
        pathcol.set_offsets(particles[i])
        return [pathcol]
    
    fig = plt.figure()
    xs, ys = zip(*particles)
    xmin, xmax = min(xs), max(xs)
    ymin, ymax = min(ys), max(ys)
    ax = plt.axes(xlim=(xmin, xmax), ylim=(ymin, ymax))
    pathcol = plt.scatter([], [], s=100)
    
    anim = animation.FuncAnimation(
        fig, update, init_func=init, fargs=(pathcol, particles), interval=1000, frames=T, 
        blit=True, repeat=True)
    plt.show()
    
    0 讨论(0)
  • 2020-12-07 05:51

    I finally found a solution. You can do it simply by using this script. I tried to keep it simple:

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.animation import FuncAnimation
    
    # Helps me to get the data from the file I want to plot
    N = 0
    
    # Load particle positioins
    with open('//home//user//data.dat', 'r') as fp:
        particles = []
        for line in fp:
            line = line.split() 
            particles.append(line)
    
    # Create new Figure and an Axes which fills it.
    fig = plt.figure(figsize=(7, 7))
    ax = fig.add_axes([0, 0, 1, 1], frameon=True)
    border = 100
    ax.set_xlim(-border, border), ax.set_xticks([])
    ax.set_ylim(-border, border), ax.set_yticks([])
    
    # particle data
    p = 18 # number of particles
    myPa = np.zeros(p, dtype=[('position', float, 2)])
    
    # Construct the scatter which we will update during animation
    scat = ax.scatter(myPa['position'][:, 0], myPa['position'][:, 1])
    
    def update(frame_number):
        # New positions
        myPa['position'][:] = particles[N*p:N*p+p]
    
        # Update the scatter collection, with the new colors, sizes and positions.
        scat.set_offsets(myPa['position'])
        increment()
    
    def increment():
        global N
        N = N+1
    
    # Construct the animation, using the update function as the animation director.
    animation = FuncAnimation(fig, update, interval=20)
    
    plt.show()
    
    0 讨论(0)
提交回复
热议问题