微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

同时使用动画和小部件 matplotlib

如何解决同时使用动画和小部件 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 举报,一经查实,本站将立刻删除。