Python 如何制作多个移动点的动画?
我正在尝试制作一个脚本,它将显示100个移动点的动画。每一个点都要走100步,然后,每一个点都会被另一个点所取代,而这个点又会走100步。我想做这个过程,比如1k次(1000代点数)。在每一代人中-100分可以完成100步。我从pickles中读取坐标,但我不知道如何设置这些动作的动画。我写了一些代码,但我知道这是错误的,我不知道下一步该怎么做。 我在等待帮助;) 注:坐标另存为张量Python 如何制作多个移动点的动画?,python,matplotlib,Python,Matplotlib,我正在尝试制作一个脚本,它将显示100个移动点的动画。每一个点都要走100步,然后,每一个点都会被另一个点所取代,而这个点又会走100步。我想做这个过程,比如1k次(1000代点数)。在每一代人中-100分可以完成100步。我从pickles中读取坐标,但我不知道如何设置这些动作的动画。我写了一些代码,但我知道这是错误的,我不知道下一步该怎么做。 我在等待帮助;) 注:坐标另存为张量 import numpy as np import matplotlib.pyplot as plt from
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
是一个巨大的文件,其内容如下所示:
output = open("output.txt", "wb")
for i in range(number_of_points):
self.points[i].point_step()
points = { i: self.points[i].point_location }
pickle.dump(points, output)
output.close()
如果我理解正确的话,文件
output.txt
,包含一系列的pickled dict。
每一条格言都是这样的形式
{ i: self.points[i].point_location }
每次调用update
都应从该文件中读取100(新)条指令。
我们可以通过制作一个,get_data
,从文件中一次生成一个项目来实现这一点。然后定义
data = get_data(path)
在update
外部,并将其作为参数传递给update
(使用)。在update
内部,循环
for point, coordinate in itertools.islice(data, 100):
遍历数据中的100项。由于data
是一个函数,因此每次调用它时将从data
中生成100个新项
请上传output.txt文件好吗?update
将i
作为参数,但在update
函数体中,您也在使用表示范围(100)
内的i。如果删除循环的
,则FuncAnimation
将调用update
,并将一个帧号作为参数传递给update
。如果output.txt
文件不是太大,则在update
函数之外读取所有数据会更有效,将所有数据加载到一个全局变量中,然后将xdata
和ydata
定义为update
中该数据的切片。该文件很大,但关键是我在范围内为I保存数据,如:output=open(“output.txt”,“wb”)(点数):self.points[i].point\u step()代理={i:self.points[i].point\u location}pickle.dump(points,output)output.close()好的。我认为这是可行的,但要确定它,我需要每个点的id。假设在保存点时点的id是“I”={I:self.points[I].point_location}。如何绘制点的编号而不是红点?动画非常混乱,很难说是否有效。如何在绘图中添加生成计数器和步骤?抱歉,我问了很多问题,但我是matplotlib的新手。谢谢你的帖子:)而不是为绘图编号设置动画,给每个点指定一种不同的颜色怎么样?对于100个点来说,颜色是难以辨认的。但是对于数字,如果我设置一个适当的间隔,应该可以很容易地观察到单个点是如何改变位置的。
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()