Matplotlib:如何为越来越多的随机数设置动画?

时间:2018-01-18 00:33:03

标签: python animation matplotlib numbers

我正在尝试使用Matplotlib和MoviePy为一系列随机数设置动画。

我想要这个系列:

  • 一旦到达上一行的末尾就继续到下一行
  • 每次增长时都会完全改变1(生成新序列)

整件事应该是这样的:

enter image description here 到目前为止,我唯一能做的就是:

enter image description here

(荒谬......我知道)

from moviepy.video.io.bindings import mplfig_to_npimage
import moviepy.editor as mpy

def moving_numbers(t):
    tf = plt.figure()
    plt.axis('off')
    plt.text(t, 1, np.random.randint(0, 9), fontsize = 24)
    return mplfig_to_npimage(tf)

animation =  mpy.VideoClip(moving_numbers, duration = 2)
animation.write_gif("tf.gif", fps=20)

知道如何改进这个片段吗?

2 个答案:

答案 0 :(得分:1)

以下是问题中所需的随机数动画的纯matplotlib实现。

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
import textwrap

nc = 9 # number of characters per line
nl = 6 # number of lines

fig,ax = plt.subplots(figsize=(2,2))
ax.axis("off")

text = ax.text(0,1,"", ha="left", va="top", size=16,
               transform=ax.transAxes)
tw = textwrap.TextWrapper(width=nc)

def update(i):
    h = np.random.randint(0,10,size=i).astype(str)
    t = "".join(h)
    t = tw.fill(t)
    text.set_text(t)

ani = FuncAnimation(fig, update, frames=nc*nl+1, interval=100)
ani.save("anim.gif", writer="imagemagick")
plt.show()

enter image description here

答案 1 :(得分:1)

在@ ImportanceOfBeingErnest的答案的基础上,但使用你的代码,你会有类似的东西:

digits_per_line = 9
new_digits_every_second = 3
wrapper = textwrap.TextWrapper(width=digits_per_line)

def moving_numbers(t):
    n_digits = int(new_digits_every_second * t)
    digits = np.random.randint(0, 10, size=n_digits).astype(str)
    number = "".join(digits)
    wrapped_number = wrapper.fill(number)
    tf = plt.figure()
    plt.axis('off')
    plt.text(0, 0, wrapped_number, fontsize=24)
    return mplfig_to_npimage(tf)

编辑:使用@ ImportanceOfBeingErnest的技术避免每次重绘:

digits_per_line = 9
new_digits_every_second = 3
wrapper = textwrap.TextWrapper(width=digits_per_line)

tf = plt.figure()
plt.axis('off')
text = plt.text(0, 0, '', a="left", va="top", fontsize=24)

def moving_numbers(t):
    n_digits = int(new_digits_every_second * t)
    digits = np.random.randint(0, 10, size=n_digits).astype(str)
    number = "".join(digits)
    wrapped_number = wrapper.fill(number)
    text.set_text(wrapped_number)
    return mplfig_to_npimage(tf)