matplotlib 如何更新散点图动画[复制]

mbzjlibv  于 2023-11-22  发布在  其他
关注(0)|答案(2)|浏览(135)

此问题在此处已有答案

How to animate a scatter plot(5个答案)
9天前关闭
我试着写一个简单的脚本,更新每个时间步t的散点图。我想尽可能简单地做。但它所做的就是打开一个窗口,我什么也看不到。窗口只是冻结。这可能只是一个小错误,但我找不到它。
data.dat的格式为

x      y
Timestep 1      1      2
                3      1
Timestep 2      6      3
                2      1

字符串
(the文件只包含数字)

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

# Load particle positioins
with open('//home//user//data.dat', 'r') as fp:
    particles = []
    for line in fp:
        line = line.split() 
        if line:
            line = [float(i) for i in line]
            particles.append(line)

T = 100
numbParticles = 2

x, y = np.array([]), np.array([])

plt.ion()
plt.figure()
plt.scatter(x,y)
for t in range(T):
    plt.clf()
    for k in range(numbP):
            x = np.append(x, particles[numbParticles*t+k][0])
            y = np.append(y, particles[numbParticles*t+k][1])
    plt.scatter(x,y)
    plt.draw()
    time.sleep(1)
    x, y = np.array([]), np.array([])

0vvn1miw

0vvn1miw1#

我终于找到了一个解决方案。你可以通过使用这个脚本来简单地完成它。我试图保持简单:

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()

字符串

o0lyfsai

o0lyfsai2#

制作动画最简单、最干净的方法是使用matplotlib.animation模块,如下面的Matplotlib Animation Tutorial所示。
因为散点图返回matplotlib.collections.PathCollection,所以更新它的方法是调用它的set_offsets方法。您可以向它传递一个shape(N,2)数组或N个二元组的列表-每个二元组是(x,y)坐标。
比如说,

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

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 = FuncAnimation(fig, update, init_func=init, fargs=(pathcol, particles),
                     interval=1000, frames=T, blit=True, repeat=True)
plt.show()

字符串
循环在FuncAnimation()内部,所以你看不到它。如果你愿意,你可以看看source code(实际上那里没有循环,而是一个迭代器),但你也可以接受从外部看到的FuncAnimation(fig, update, interval=1000, frames=100)每1000 ms调用一次函数update,并将i递增1,直到frames给出的数字。

相关问题