2

I am trying to figure out how to speed up this animation. I want the whole thing to finish at 30 seconds.

I've tried adjusting the interval between frames, the save count, inside FuncAnimation, but it doesn't seem to work. Is there anyway to just set the total duration and have matplotlib squeeze everything into that time limit?

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation #1
n = 500
x = np.random.randn(n)

%matplotlib notebook

# generate 4 random variables from the random, gamma, exponential, and uniform distributions
x1 = np.random.normal(-2.5, 1, 10000)
x2 = np.random.gamma(2, 1.5, 10000)
x3 = np.random.exponential(2, 10000)+7
x4 = np.random.uniform(14,20, 10000)

def update(curr):
    # check if animation is at the last frame, and if so, stop the animation a
    if curr == n: 
        a.event_source.stop()

    plt.cla()
    plt.hist(x1[:curr], normed=True, bins=20, alpha=0.5)
    plt.hist(x2[:curr], normed=True, bins=20, alpha=0.5)
    plt.hist(x3[:curr], normed=True, bins=20, alpha=0.5)
    plt.hist(x4[:curr], normed=True, bins=20, alpha=0.5)
    plt.axis([-7,21,0,0.6])
    plt.text(x1.mean()-1.5, 0.5, 'Normal')
    plt.text(x2.mean()-1.5, 0.5, 'Gamma')
    plt.text(x3.mean()-1.5, 0.5, 'Exponential')
    plt.text(x4.mean()-1.5, 0.5, 'Uniform')

    plt.annotate('n = {}'.format(curr), [3,27])

fig = plt.figure()
fig = plt.figure(figsize=(9,3))
a = animation.FuncAnimation(fig, update, interval=10, blit=True, save_count=500)

The final product looks like this:

enter image description here

ZakS
  • 1,073
  • 3
  • 15
  • 27
  • The code as you show it will not run. (After posting copy the code from the question and try to run it to prevent such things from happening.) – ImportanceOfBeingErnest May 09 '18 at 13:00
  • @ImportanceOfBeingErnest thank you, I will try to do do so going fwds. I was missing a comma at the end, in "blit=True save_count=500". I have edited the code to reflect this. Any advice is very welcome. – ZakS May 09 '18 at 15:56
  • @ImportanceOfBeingErnest I see that you answered the same question a year ago. Here: https://stackoverflow.com/questions/42910622/animation-of-histograms-in-subplot . I have left a question for you there in case it is possible to check it. Regarding the importance of clearing the axes. – ZakS May 10 '18 at 21:08

1 Answers1

0

I have been given a suggested answer:

...
def update(curr)
  x = 100 #x as speed multiplier
  curr = curr*x 
  if curr >= n:
    a.event_source.stop()

...

The logic is basically to speed up the rate at which FuncAnimate plots each graph by taking a larger subsection of the array of values.

ZakS
  • 1,073
  • 3
  • 15
  • 27