gpt4 book ai didi

python - Matplotlib funcanimation blit 慢

转载 作者:行者123 更新时间:2023-11-28 16:40:33 25 4
gpt4 key购买 nike

我在 Matplotlib 中遇到动画缓慢的问题。我正在对模拟结果进行动画处理,这是最简单的可视化方式,其中包含一系列随时间改变颜色的矩形。

遵循建议 here ,我使用 blitting 仅绘制每帧中变化的(一小部分)矩形。我也尝试使用 FuncAnimation 来实现它,但是当它与 Blit=True 一起使用时,脚本运行速度要慢得多。

我想知道这是否是因为我将所有 的矩形返回给 FuncAnimation,所以即使它们没有改变,它也会重新绘制所有这些矩形。有没有办法将每一帧的不同艺术家传递给 FuncAnimation?我尝试只传递一个已更改的元组(“动画”函数中注释掉的 block ),但这导致看似随机的动画帧......

使用:

$ python2 [script].py blit
$ python2 [script].py anim

谢谢!

import sys
import numpy as np
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
import matplotlib.animation as manim

def animate_data(plot_type):
"""
Use:
python2 plot_anim.py [option]
option = anim OR blit
"""

# dimension parameters
Nx = 30
Ny = 20
numtimes = 100
size = 0.5

if plot_type == "blit":
# "interactive mode on"
plt.ion()
# Prepare to do initial plot
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.set_aspect('equal', 'box')
ax.xaxis.set_major_locator(plt.NullLocator())
ax.yaxis.set_major_locator(plt.NullLocator())
# An array in which to store the rectangle artists
rects = np.empty((Nx, Ny), dtype=object)
# Generate initial figure of all green rectangles
for (i,j),k in np.ndenumerate(rects):
color = 'green'
rects[i, j] = plt.Rectangle([i - size / 2, j - size / 2],
size, size, facecolor=color, edgecolor=color)
ax.add_patch(rects[i, j])
ax.autoscale_view()

# "Old" method using fig.canvas.blit()
if plot_type == "blit":
plt.show()
fig.canvas.draw()
# Step through time updating the rectangles
for tind in range(1, numtimes):
updated_array = update_colors(rects)
for (i, j), val in np.ndenumerate(updated_array):
if val:
ax.draw_artist(rects[i, j])
fig.canvas.blit(ax.bbox)

# New method using FuncAnimate
elif plot_type == "anim":
def animate(tind):
updated_array = update_colors(rects)
# # Just pass the updated artists to FuncAnimation
# toupdate = []
# for (i, j), val in np.ndenumerate(updated_array):
# if val:
# toupdate.append(rects[i, j])
# return tuple(toupdate)
return tuple(rects.reshape(-1))
ani = manim.FuncAnimation(fig, animate, frames=numtimes,
interval=10, blit=True, repeat=False)
plt.show()

return

# A function to randomly update a few rectangles
def update_colors(rects):
updated_array = np.zeros(rects.shape)
for (i, j), c in np.ndenumerate(rects):
rand_val = np.random.rand()
if rand_val < 0.003:
rects[i, j].set_facecolor('red')
rects[i, j].set_edgecolor('red')
updated_array[i, j] = 1
return updated_array

if __name__ == "__main__":
if len(sys.argv) > 1:
plot_type = sys.argv[1]
else:
plot_type = "blit"
animate_data(plot_type)

最佳答案

每帧更新 600 个矩形非常慢,代码中的 cbar_blit 模式更快,因为您只更新颜色发生变化的矩形。您可以使用 PatchCollection 来加速绘图,这里是代码:

import numpy as np
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
import matplotlib.animation as manim
from matplotlib.collections import PatchCollection

Nx = 30
Ny = 20
numtimes = 100

size = 0.5

x, y = np.ogrid[-1:1:30j, -1:1:20j]

data = np.zeros((numtimes, Nx, Ny))

for i in range(numtimes):
data[i] = (x-i*0.02+1)**2 + y**2

colors = plt.cm.rainbow(data)

fig, ax = plt.subplots()

rects = []
for (i,j),c in np.ndenumerate(data[0]):
rect = plt.Rectangle([i - size / 2, j - size / 2],size, size)
rects.append(rect)

collection = PatchCollection(rects, animated=True)

ax.add_collection(collection)
ax.autoscale_view(True)


def animate(tind):
c = colors[tind].reshape(-1, 4)
collection.set_facecolors(c)
return (collection,)

ani = manim.FuncAnimation(fig, animate, frames=numtimes,
interval=10, blit=True, repeat=False)

plt.show()

关于python - Matplotlib funcanimation blit 慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19843700/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com