如何制作多个运动点的动画?

时间:2019-08-28 17:30:05

标签: python matplotlib

我正在尝试制作一个脚本,以显示100个移动点的动画。每个点将要走100步,之后,每个点将被不同的点代替,这将再走100步。我想做1k次(1000代积分)的过程。在每一代中-100点可以执行100步。我从泡菜中读取坐标,但是我不知道该如何设置动画效果。我写了一些代码,但我有点知道这是错误的,我不知道下一步该怎么做。 我正在等待帮助;) PS .:坐标另存为张量

<?php
$loggedIn = $_SESSION["loggedin"];

if ($loggedIn == 1) {
  echo '<a id="loginBtn" class="btn btn-primary myButtons" href="/logout.php">Ausloggen</a>';
} else {
  echo '<a id="loginBtn" class="btn btn-primary myButtons" href="/login.php">Anmelden</a>';
}
?>

import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation import pickle fig, ax = plt.subplots() xdata, ydata = [], [] ln, = plt.plot([], [], 'ro') def init(): ax.set_xlim(0, 20) ax.set_ylim(0, 20) return ln, def update(i): with open("output.txt", "rb") as file: try: while True: for point, coordinate in pickle.load(file).items(): for i in range(100): if point == i: xdata.append(coordinate.cpu().numpy()[0]) ydata.append(coordinate.cpu().numpy()[1]) ln.set_data(xdata, ydata) return ln, except EOFError: pass ani = FuncAnimation(fig, update, np.arange(1, 1000), init_func=init, blit=True) plt.show() 是一个巨大的文件,其内容生成如下:

output.txt

1 个答案:

答案 0 :(得分:0)

如果我理解正确,文件output.txt包含一系列腌制的字典。 每个字典的格式都是

{ i: self.points[i].point_location }

每次调用update都应从该文件中读取100(新)格。 我们可以通过制作generator functionget_data来做到这一点,它一次从文件中产生一项。然后定义

data = get_data(path)

update之外,并将其作为参数传递给update(使用FuncAnimation's fargs parameter。)在update内,循环

for point, coordinate in itertools.islice(data, 100):

反复浏览data中的100个项目。由于dataiterator,因此itertools.islice每次被调用时将从data中产生100个 new 项目。


import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import pickle
import itertools as IT


def init():
    ax.set_xlim(0, 20)
    ax.set_ylim(0, 20)
    return (pathcol,)


def pickleLoader(f):
    """
    Return generator which yields unpickled objects from file object f
    # Based on https://stackoverflow.com/a/18675864/190597 (Darko Veberic)
    """
    try:
        while True:
            yield pickle.load(f)
    except EOFError:
        pass


def get_data(path):
    with open(path, "rb") as f:
        for dct in pickleLoader(f):
            yield from dct.items()


def update(i, data, pathcol, texts, title, num_points):
    title.set_text("Generation {}".format(i))
    xdata, ydata, color = [], [], []
    for point, coordinate in IT.islice(data, num_points):
        texti = texts[point]
        x, y = coordinate.cpu().numpy()
        xdata.append(x)
        ydata.append(y)
        color.append(point)
        texti.set_position((x, y))
    color = np.array(color, dtype="float64")
    color /= num_points
    pathcol.set_color = color
    pathcol.set_offsets(np.column_stack([xdata, ydata]))

    return [pathcol, title] + texts


class Coord:
    # just to make the code runnable
    def __init__(self, coord):
        self.coord = coord

    def cpu(self):
        return Cpu(self.coord)


class Cpu:
    # just to make the code runnable
    def __init__(self, coord):
        self.coord = coord

    def numpy(self):
        return self.coord


def make_data(path, num_frames=1000, num_points=100):
    # just to make the code runnable
    with open(path, "wb") as output:
        for frame in range(num_frames):
            for i in range(num_points):
                points = {i: Coord(20 * np.random.random((2,)))}
                pickle.dump(points, output)


def _blit_draw(self, artists, bg_cache):
    # https://stackoverflow.com/a/17562747/190597 (tacaswell)
    # Handles blitted drawing, which renders only the artists given instead
    # of the entire figure.
    updated_ax = []
    for a in artists:
        # If we haven't cached the background for this axes object, do
        # so now. This might not always be reliable, but it's an attempt
        # to automate the process.
        if a.axes not in bg_cache:
            # bg_cache[a.axes] = a.figure.canvas.copy_from_bbox(a.axes.bbox)
            # change here
            bg_cache[a.axes] = a.figure.canvas.copy_from_bbox(a.axes.figure.bbox)
        a.axes.draw_artist(a)
        updated_ax.append(a.axes)

    # After rendering all the needed artists, blit each axes individually.
    for ax in set(updated_ax):
        # and here
        # ax.figure.canvas.blit(ax.bbox)
        ax.figure.canvas.blit(ax.figure.bbox)


# MONKEY PATCH!!
matplotlib.animation.Animation._blit_draw = _blit_draw

num_points = 100
num_frames = 1000
fig, ax = plt.subplots()
pathcol = ax.scatter(
    [0] * num_points, [0] * num_points, c=np.linspace(0, 1, num_points), s=100
)
title = ax.text(
    0.5,
    1.05,
    "",
    transform=ax.transAxes,
    horizontalalignment="center",
    fontsize=15,
    animated=True,
)

texts = []
for i in range(num_points):
    t = ax.text(0, 0, str(i), fontsize=10, animated=True)
    texts.append(t)

path = "/tmp/output.txt"
make_data(path, num_frames, num_points)  # just to make the code runnable
data = get_data(path)

ani = FuncAnimation(
    fig,
    update,
    range(1, num_frames + 1),
    init_func=init,
    blit=True,
    fargs=(data, pathcol, texts, title, num_points),
    interval=1000,  # decrease to speed up the animation
    repeat=False,
)
plt.show()