matplotlib FuncAnimation не запускается при нажатии кнопки на событии виджета - PullRequest
0 голосов
/ 06 августа 2020

matplotlib noob здесь.

Я пытаюсь создать анимацию (которая начинается при нажатии кнопки) заполняемого нормального распределения, где параметры распределения (среднее и стандартное отклонение) выбираются с помощью двух ползунков виджеты.

Помогите пожалуйста. Я вставил свой код ниже

%matplotlib notebook
from pdb import set_trace as bp
import matplotlib.animation as animation
import numpy as np
from matplotlib.widgets import Slider, Button, RadioButtons


fig = plt.figure()

n = 1000

x = np.array([])
bins = np.arange(-4, 4, 0.5)

plt.hist(x, bins=bins)
plt.subplots_adjust(bottom=0.25)

def update(curr):
    if curr == n: 
        a.event_source.stop()

    plt.cla()
    plt.hist(x[:curr], bins=bins)
    plt.axis([-4,4,0,500])
    plt.gca().set_title('Sampling the Normal Distribution')
    plt.gca().set_ylabel('Frequency')
    plt.gca().set_xlabel('Value')
    plt.annotate('n = {}'.format(curr), [3,480])

axcolor = 'lightgoldenrodyellow'
axmu = plt.axes([0.15, 0.1, 0.65, 0.03], facecolor=axcolor)
axstdev = plt.axes([0.15, 0.15, 0.65, 0.03], facecolor=axcolor)

muslider = Slider(axmu, 'mean', 0.1, 30.0, valinit=0)
stdevslider = Slider(axstdev, 'stdev', 0.1, 10.0, valinit=1.0)

startax = plt.axes([0.4, 0.025, 0.1, 0.04])
startbutton = Button(startax, 'Start', color=axcolor, hovercolor='0.975')

newmean = 0
newstdev = 1.0

def getnewparams(val):
    global newmean
    global newstdev
    newmean = muslider.val
    newstdev = stdevslider.val
    
def startanimation(event):
    print(f"params now is {newmean} {newstdev}")
    global x
    x = np.random.normal(loc=newmean, scale=newstdev, size=n)

    a = animation.FuncAnimation(fig, update, interval=100)
    a.event_source.start()
    
muslider.on_changed(getnewparams)
stdevslider.on_changed(getnewparams)
startbutton.on_clicked(startanimation)

Как теперь выглядит мой график

1 Ответ

0 голосов
/ 06 августа 2020

Используя предложение @ jasonharper, я смог решить проблему самостоятельно. Я вставляю рабочий код ниже

%matplotlib notebook
import matplotlib.pyplot as plt
from pdb import set_trace as bp
import matplotlib.animation as animation
import numpy as np
from matplotlib.widgets import Slider, Button, RadioButtons


fig = plt.figure()

n = 1000

a = None
x = np.array([])
# bins = np.arange(-4, 4, 0.5)

plt.hist(x, bins=bins)
plt.subplots_adjust(bottom=0.25)
histaxis = plt.gca()

def update(curr):
    if curr == n: 
        a.event_source.stop()

    histaxis.cla()
    histaxis.hist(x[:curr], bins=100)
    # histaxis.axis([-4,4,0,500])
    histaxis.set_title('Sampling the Normal Distribution')
    histaxis.set_ylabel('Frequency')
    histaxis.set_xlabel('Value')
    histaxis.annotate('n = {}'.format(curr), [3,480])

axcolor = 'lightgoldenrodyellow'
axmu = plt.axes([0.15, 0.1, 0.65, 0.03], facecolor=axcolor)
axstdev = plt.axes([0.15, 0.15, 0.65, 0.03], facecolor=axcolor)

muslider = Slider(axmu, 'mean', 0.1, 30.0, valinit=0)
stdevslider = Slider(axstdev, 'stdev', 0.1, 10.0, valinit=1.0)

startax = plt.axes([0.4, 0.025, 0.1, 0.04])
startbutton = Button(startax, 'Start', color=axcolor, hovercolor='0.975')

newmean = 0
newstdev = 1.0

def getnewparams(val):
    global newmean
    global newstdev
    newmean = muslider.val
    newstdev = stdevslider.val
    
def startanimation(event):
    print(f"params now is {newmean} {newstdev}")
    global x
    x = np.random.normal(loc=newmean, scale=newstdev, size=n)

    global a
    a = animation.FuncAnimation(fig, update, interval=100)
    a.event_source.start()
    
muslider.on_changed(getnewparams)
stdevslider.on_changed(getnewparams)
startbutton.on_clicked(startanimation)
...