【发布时间】:2022-01-04 20:19:34
【问题描述】:
我试图从一个点开始画一条长线,然后在一定时间后创建新点,这将是该线的下一个点。所以它应该看起来像一条路径。但是我遇到了一个问题,当线路变长时,计算机出现计算问题并且开始滞后。我认为,该程序应该在此期间以相同的速度运行,除非它在磁盘上使用成倍增加的空间或再次绘制相同的点。不知道是什么原因造成了这些困难,请您提出一些方法,如何改善它?
这是我的代码示例:
import matplotlib.pyplot as plt
import random
import matplotlib.animation as animation
CELLS: list = []
# number of cells
NUM_CELLS: int = 100
# how big is the move
MAX_STEP: int = 10
# how many ms does it take to update → higher means slower
SPEED: int = 10
fig = plt.figure()
plt.xlim(0, 1000)
plt.ylim(0, 1000)
plt.axis("off")
def create_cell():
y_coord = random.randint(0, 1000)
x_coord = random.randint(0, 1000)
CELLS.append([x_coord, y_coord])
def move(self):
new_cells = []
for cell in CELLS:
x_coord1 = cell[0]
y_coord1 = cell[1]
move_x = random.randint(-1, 1)
move_y = random.randint(-1, 1)
x_coord2 = cell[0] + (MAX_STEP * move_x)
y_coord2 = cell[1] + (MAX_STEP * move_y)
x_coords = [x_coord1, x_coord2]
y_coords = [y_coord1, y_coord2]
plt.plot(x_coords, y_coords, color="blue")
new_cells.append([x_coord2, y_coord2])
CELLS.clear()
for point in new_cells:
CELLS.append(point)
for i in range(NUM_CELLS):
create_cell()
animator = animation.FuncAnimation(fig, move, frames=100, interval = SPEED)
plt.show()
【问题讨论】:
-
文档中的一个简单示例完全符合您的要求:matplotlib.org/stable/api/animation_api.html
-
谢谢。它帮助了我,这是我一直在寻找的。现在,它正在工作
标签: python performance matplotlib