好吧,我想创建一个可以显示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时是否需要了解一些细节?
答案 0 :(得分:0)
GridSpec参数wspace
和hspace
与plt.tight_layout
不兼容。您可以使用tight_layout
或指定间距。
如果您想使用GridSpec,您有两个选择:
plt.tight_layout
行gspec.update(wspace = .6, hspace = .6)
行原因
fig, ((ax1,ax2),(ax3, ax4)) = plt.subplots(2, 2, sharey = True)
ax = [ax1, ax2, ax3, ax4]
因此,您不设置任何wspace或hspace。