Well, I want to make an animation which can show 4 different distributions, but when I use gridspec to make subplots, it doesn't work, the code is below:
import matplotlib.animation as animation
import matplotlib.pyplot as plt
import numpy as np
%matplotlib notebook
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)
x = [x1, x2, x3, x4]
bins1 = np.arange(-7.5, 2.5, 0.2)
bins2 = np.arange(0, 10, 0.2)
bins3 = np.arange(7, 17, 0.2)
bins4 = np.arange(12, 22, 0.2)
bins = [bins1, bins2, bins3, bins4]
axis1 = [-7.5, 2.5, 0, 0.6]
axis2 = [0, 10, 0, 0.6]
axis3 = [7, 17, 0, 0.6]
axis4 = [12, 22, 0, 0.6]
axis = [axis1, axis2, axis3, axis4]
import matplotlib.gridspec as gridspec
gspec = gridspec.GridSpec(4, 4)
plt.figure()
ax1 = plt.subplot(gspec[0:2, 0:2])
ax2 = plt.subplot(gspec[0:2, 2:])
ax3 = plt.subplot(gspec[2:, 2:])
ax4 = plt.subplot(gspec[2:, 0:2])
ax = [ax1, ax2, ax3, ax4]
for a in ax:
a.spines['right'].set_visible(False)
a.spines['top'].set_visible(False)
gspec.update(wspace = .6, hspace = .6)
def update(curr):
if curr == 500:
a.event_source.stop()
for i in range(len(ax)):
ax[i].cla()
ax[i].hist(x[i][:curr], normed = True, bins = bins[i])
ax[i].axis(axis[i])
ax[i].set_title('n={}'.format(curr))
ax[i].set_ylabel('Normed Frequency')
plt.tight_layout()
fig = plt.gcf()
a = animation.FuncAnimation(fig, update, interval = 10)
in this case, the animation doesn't work, but the funny thing is if I use
fig, ((ax1,ax2),(ax3, ax4)) = plt.subplots(2, 2, sharey = True)
ax = [ax1, ax2, ax3, ax4]
to make ax1,ax2,ax3,ax4 and don't change anything else, the code works well, so are there some details need to know when using gridspec?
See Question&Answers more detail:
os