I am trying to animate multiple histograms simultaneously. The animation is intended to incrementally visualize the samples that follow four different distributions (Normal, Gamma, Exponential and Uniform).
I have read and been able to iterate on the matplotlib animation docs' example with multiple subplots using the following thread Animate multiple shapes in python3 using matplotlib. However, determining the random variables prior to the "update" function and trying to incrementally update histograms with an animation is causing me issues that I cannot seem to get around. Matplotlib version: 3.0.2
Code that animates a single histogram (that works)
import matplotlib.animation as animation
import numpy as np
n = 100
x = np.random.normal(loc=2.5, scale=1.0, size=n)
fig, (ax1, ax2, ax3, ax4) = plt.subplots(4, 1, sharex=True, sharey=True)
def update(curr):
if curr == n:
a.event_source.stop()
plt.cla()
bins = np.arange(-2, 5, 0.5)
ax1.hist(x[:curr], bins=bins)
plt.axis([-2, 6, 0, 30])
ax1.set_title('Sampling the Normal Distribution')
plt.gca().set_ylabel('Frequency')
plt.gca().set_xlabel('Value')
plt.annotate('n = {}'.format(curr), [3,27])
a = animation.FuncAnimation(fig, update, interval=100)
plt.show()
My attempt at animating multiple subplots (does not produce expected result)
n = 100
x1 = np.random.normal(loc=2.5, scale=1.0, size=n)
x2 = np.random.gamma(shape=2.0, scale=1.0, size=n)
x3 = np.random.exponential(scale=1.0, size=n)
x4 = np.random.uniform(low=0, high = 5, size=n)
data = [x1, x2, x3, x4]
dist = ['Normal', 'Gamma', 'Exponential', 'Uniform']
bins = np.arange(-2,6,0.5) # generate range for bins
# plot the histograms
fig, (ax1,ax2,ax3,ax4) = plt.subplots(4, 1, sharex=True, sharey=True)
def update(curr):
if curr == n:
a.event_source.stop()
plt.cla()
ax1.hist(x1[:curr], normed=True, bins=bins, color='blue')
ax2.hist(x2[:curr], normed=True, bins=bins, color='red')
ax3.hist(x3[:curr], normed=True, bins=bins, color='green')
ax4.hist(x4[:curr], normed=True, bins=bins, color='gray')
a = animation.FuncAnimation(fig, update, interval=100)
plt.show()
Code that produces expected end result graph (without animation)
n = 100
x1 = np.random.normal(loc=2.5, scale=1.0, size=n)
x2 = np.random.gamma(shape=2.0, scale=1.0, size=n)
x3 = np.random.exponential(scale=1.0, size=n)
x4 = np.random.uniform(low=0, high = 5, size=n)
data = [x1, x2, x3, x4]
dist = ['Normal', 'Gamma', 'Exponential', 'Uniform']
bins = np.arange(-2,6,0.5) # generate range for bins
# plot the histograms
fig, (ax1,ax2,ax3,ax4) = plt.subplots(4, 1, sharex=True, sharey=True)
ax1.hist(x1, normed=True, bins=bins, color='blue')
ax2.hist(x2, normed=True, bins=bins, color='red')
ax3.hist(x3, normed=True, bins=bins, color='green')
ax4.hist(x4, normed=True, bins=bins, color='gray')
plt.show()