在matplotlib中使用滑块不更新子批次

在matplotlib中使用滑块不更新子批次,matplotlib,slider,Matplotlib,Slider,我不确定我用滑块到底做错了什么。一旦滑块值被修改,它就不会更新。我已经被困很长时间了,任何线索都会有帮助的。提前谢谢 import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import Slider, Button, RadioButtons import matplotlib.animation as animation plt.cla() n = 1000 x1 = np.random.nor

我不确定我用滑块到底做错了什么。一旦滑块值被修改,它就不会更新。我已经被困很长时间了,任何线索都会有帮助的。提前谢谢

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button, RadioButtons
import matplotlib.animation as animation

plt.cla()

n = 1000
x1 = np.random.normal(5, 1, n)
x2 = np.random.gamma(2, 1.5, n)
x3 = np.random.exponential(2, n)
x4 = np.random.uniform(0,10, n)

fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2,sharey=True,sharex = True)
plt.axis([0,10,0,600])
axs = [ax1,ax2,ax3,ax4]

ax1.hist(x1, density=False, bins=10, alpha=0.5)
ax2.hist(x2, density=False, bins=10, alpha=0.5)
ax3.hist(x3, density=False, bins=10, alpha=0.5)
ax4.hist(x4, density=False, bins=10, alpha=0.5)

axcolor = 'lightgoldenrodyellow'
axfreq = plt.axes([.2,.01,.65,.02], facecolor=axcolor)
sample_slider = DiscreteSlider(axfreq, 'Sample Size \n (100-1000)', 100, 1000, valinit=1000)

def update(val):
    n = sample_slider.val
    print(n)
    
    plt.annotate('n = {}'.format(n), [9,15])
    
    ax1.cla()
    ax2.cla()
    ax3.cla()
    ax4.cla()
    
    x_1 = np.random.normal(5, 1, n)
    x_2 = np.random.gamma(2, 1.5, n)
    x_3 = np.random.exponential(2, n)
    x_4 = np.random.uniform(0,10, n)
    
    plt.axis([0,10,0,500])
    ax1.hist(x_4, density=False, bins=10, alpha=0.5)
    ax2.hist(x_3, density=False, bins=10, alpha=0.5)
    ax3.hist(x_2, density=False, bins=10, alpha=0.5)
    ax4.hist(x_1, density=False, bins=10, alpha=0.5)
    
    fig.canvas.draw_idle()
           
sample_slider.on_changed(update)

plt.show()
离散滑块-我在课堂上跑步

类离散滑块(滑块): “”“带有离散步骤的matplotlib滑块小部件。”“” definit(self,*args,**kwargs): “”“与滑块相同。init,但“增量”kwarg除外。”。 “增量”指定滑块将被取消书写的步长 到 self.inc=kwargs.pop('增量',50) 滑块。init(self,*args,**kwargs) self.val=1

def set_val(self, val):
    discrete_val = int(val / self.inc) * self.inc
    # We can't just call Slider.set_val(self, discrete_val), because this 
    # will prevent the slider from updating properly (it will get stuck at
    # the first step and not "slide"). Instead, we'll keep track of the
    # the continuous value as self.val and pass in the discrete value to
    # everything else.
    xy = self.poly.xy
    xy[2] = discrete_val, 1
    xy[3] = discrete_val, 0
    self.poly.xy = xy
    self.valtext.set_text(self.valfmt % discrete_val)
    if self.drawon: 
        self.ax.figure.canvas.draw()
    self.val = val
    if not self.eventson: 
        return
    for cid, func in self.observers.items():
        func(discrete_val)