Python Matplotlib Update Scatter

后端 未结 2 668
独厮守ぢ
独厮守ぢ 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: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()
    

提交回复
热议问题