好吧,我想制作一个可以显示4种不同分布的动画,但是当我使用gridspec制作子图时,它不起作用,代码如下:
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)
在这种情况下,动画不起作用,但有趣的是,如果我使用
fig, ((ax1,ax2),(ax3, ax4)) = plt.subplots(2, 2, sharey = True) ax = [ax1, ax2, ax3, ax4]
使ax1,ax2,ax3,ax4保持不变,代码运行良好,因此使用gridspec时是否需要了解一些详细信息?
GridSpec参数wspace和与hspace不兼容plt.tight_layout。您可以使用tight_layout或指定间距。
wspace
hspace
plt.tight_layout
tight_layout
如果要使用GridSpec,则有两个选择:
gspec.update(wspace = .6, hspace = .6)
原因
因此,有效的方法是您不设置任何wspace或hspace。