python 实时波形 animation_python-Matplotlib funcanimation blit缓慢

我在Matplotlib中出现动画缓慢的问题.我正在对模拟的结果进行动画处理,最简单的方法是使用随时间变化颜色的矩形阵列将其可视化.

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

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

采用:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值