gpt4 book ai didi

python - 动画在 matplotlib 上不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 15:10:36 25 4
gpt4 key购买 nike

随着样本数量的增加(从 100 到 1000),我试图使形状的动画呈现指数分布。还有一个用于配置分布的 lambda 参数的 slider 和一个用于启动动画的按钮。

我的问题是,即使布局被渲染,当我按下开始按钮时也没有动画发生。这是我迄今为止的尝试:

为了简化事情而进行了编辑,我在 Python 笔记本中运行它:

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

n0 = 100
n1 = 1000

#Create figure object
fig, ax = plt.subplots(1,1)
plt.subplots_adjust(bottom=0.3)

#Create Sliders for parameters
axlam = plt.axes([0.20, 0.05, 0.20, 0.03], facecolor=axcolor)

slam = Slider(axlam, 'Exp lambda', 0, 5, valinit=1)

#Default distributions
dexp = np.random.exponential(1, n1)

#Updates distributions when sliders are changed
def updateDist(val):
lam = slam.val
dexp = np.random.exponential(lam, n1)

slam.on_changed(updateDist)

#updates plot on FuncAnimation call
def update(curr):
if( curr == (n1-n0) ):
a.event.source.stop()
plt.cla()
bins_exp = np.arange(0,4/slam.val,0.25)
ax.hist(dexp[:(n0+curr)],bins=bins_exp)
ax.set_title('Exp n={}'.format(n0+curr))

#Define Start button and function to start animation
goax = plt.axes([0.8, 0.025, 0.1, 0.04])
button = Button(goax, 'Start', color=axcolor, hovercolor='0.975')

a = None
def start(event):
a = animation.FuncAnimation(fig,update,interval=100)
button.on_clicked(start)

最佳答案

您应该注意函数的 namespace 。

考虑

a = 0
def f():
a = 1
f()
print(a) # will print 0

因此,您需要处理实际对象,而不是它们的本地副本。

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

n0 = 100
n1 = 1000

#Create figure object
fig, ax = plt.subplots(1,1)
plt.subplots_adjust(bottom=0.3)

#Create Sliders for parameters
axcolor = "skyblue"
axlam = plt.axes([0.20, 0.05, 0.20, 0.03], facecolor=axcolor)

slam = Slider(axlam, 'Exp lambda', 0, 5, valinit=1)

#Default distributions
dexp = [np.random.exponential(1, n1)]

##Updates distributions when sliders are changed
def updateDist(val):
lam = slam.val
dexp[0] = np.random.exponential(lam, n1)

slam.on_changed(updateDist)

#updates plot on FuncAnimation call
def update(curr):
if( curr == (n1-n0) ):
a.event.source.stop()
ax.clear()
bins_exp = np.arange(0,4/slam.val,0.25)
ax.hist(dexp[0][:(n0+curr)],bins=bins_exp)
ax.set_title('Exp n={}'.format(n0+curr))
fig.canvas.draw_idle()

#Define Start button and function to start animation
goax = plt.axes([0.8, 0.025, 0.1, 0.04])
button = Button(goax, 'Start', color=axcolor, hovercolor='0.975')

a = [0]
def start(event):
a[0] = animation.FuncAnimation(fig,update,interval=100)
button.on_clicked(start)

plt.show()

关于python - 动画在 matplotlib 上不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44227474/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com