同时使用动画和小部件 matplotlib

问题描述

我有一个实践,我想同时使用动画和小部件,想法是在动画运行时更改 bins 值,我使用 Slider 更改 bins 全局值的值。但是当我运行并更改 Slider 的值时,图形消失了。我不知道为什么。

对这个问题有什么想法吗?

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
import matplotlib.gridspec as gridspec
from matplotlib.widgets import Slider

%matplotlib notebook
plt.subplot?

n = 1000
# generate 4 random variables from the random,gamma,exponential,and uniform distributions
x1 = np.random.normal(10,1,n)
x2 = np.random.gamma(2,1.5,n)
x3 = np.random.exponential(2,n)
x4 = np.random.uniform(0,20,n)
bins = 20

# plot the histograms
fig = plt.figure(figsize=(10,8))
gspec = gridspec.GridSpec(10,2)
ax1 = plt.subplot(gspec[0:3,0])
ax1.set_xlim([0,bins])
ax1.set_ylim([0,0.4])
ax2 = plt.subplot(gspec[0:3,1],sharex=ax1,sharey=ax1)
ax3 = plt.subplot(gspec[5:8,0],sharey=ax1)
ax4 = plt.subplot(gspec[5:8,sharey=ax1)
ax5 = plt.subplot(gspec[9,0:])
ax5.axes.get_yaxis().set_visible(False)
bins_slider = Slider(
    ax=ax5,label='bins',valmin=1,valmax=40,valinit=20,valfmt="%i"
)

# create the function that will do the plotting,where curr is the current frame
def update(curr):
    global bins
    # check if animation is at the last frame,and if so,stop the animation a
    vel = 100
    if vel * curr >= n: 
        a.event_source.stop()
    ax1.cla()
    ax2.cla()
    ax3.cla()
    ax4.cla()
    ax1.hist(x1[:(vel * curr)],normed=True,bins=bins)
    ax2.hist(x2[:(vel * curr)],bins=bins,color='r')
    ax3.hist(x3[:(vel * curr)],color='g')
    ax4.hist(x4[:(vel * curr)],color='y')
    ax1.set_xlim([0,bins])
    ax1.set_ylim([0,0.4])

    ax1.text(12,0.31,'x1\nnormal')
    ax2.text(12,'x2\nGamma')
    ax3.text(12,'x3\nExponential')
    ax4.text(12,'x4\nUniform')
    ax4.annotate('n = {}'.format(vel * curr),[12,0.05])

#Create widget to modify bin
def changed(val):
    bins = round(val,0)
    fig.canvas.draw_idle()

bins_slider.on_changed(changed)

#Create animation
a = animation.FuncAnimation(fig,update,interval=100)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)