Python Matplotlib更新分散 [英] Python Matplotlib Update Scatter

查看:74
本文介绍了Python Matplotlib更新分散的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图编写一个简单的脚本来更新每个时间步长t的散点图.我想做得尽可能简单.但是它所做的就是打开一个窗口,我什么也看不到.窗户冻结了.这可能只是一个小错误,但我找不到它.

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 where I can see nothing. The window just freezes. It is maybe just an small error, but I can not find it.

data.dat具有格式

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

(文件仅包含数字)

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

推荐答案

制作动画的最简单,最简洁的方法是使用

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

由于散点图返回matplotlib.collections.PathCollection,因此更新它的方法是调用其set_offsets方法.您可以向其传递形状(N,2)的数组或N个2元组的列表-每个2元组都是(x,y)坐标.

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.

例如,

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

这篇关于Python Matplotlib更新分散的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆