ICode9

精准搜索请尝试: 精确搜索

python – 如何在matplotlib中使用带有FuncAnimation的GridSpec()?

2019-10-03 03:07:13??阅读:583??来源: 互联网

标签:python?numpy?matplotlib?animation?random


好吧,我想制作一个可以显示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或指定间距.

如果您想使用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.



标签:python,numpy,matplotlib,animation,random

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有