我正在为基本的冒泡排序制作动画条形图。它运行得很好。但不会重复自身(循环)。我正在 jupyter 笔记本中尝试,我添加了 %matplotlib qt, 尽管我已将重复设置为 True ,为什么我的 animFunc 不会重复。
x=["1","2","3","4","5","6","7","8","9","10"]
y=[7,8,5,3,1,9,4,2,10,6]
temp=0
def animator_X():
for a in range(len(y)-1):
for b in range(len(y)-a-1):
if y[b]>y[b+1]:
temp = y[b]
y[b]=y[b+1]
y[b+1]=temp
yield y
fig,ax = plt.subplots(figsize=(7,5))
def init():
ax.clear()
y=[7,8,5,3,1,9,4,2,10,6]
plt.bar(x,y,color=['blue'])
def animX(i):
ax.clear()
plt.bar(x,y,color=['blue'])
return plt
animx = FuncAnimation(fig,animX,frames=animator_X,interval=1000,init_func=init,repeat=True)
plt.show()
当主
y
变量在运行后重复 init
函数时,您并没有重置它。%matplotlib notebook
import matplotlib.pyplot as plt
import matplotlib.animation as animation
x=["1","2","3","4","5","6","7","8","9","10"]
y=[7,8,5,3,1,9,4,2,10,6]
temp=0
def animator_X():
for a in range(len(y)-1):
for b in range(len(y)-a-1):
if y[b]>y[b+1]:
temp = y[b]
y[b]=y[b+1]
y[b+1]=temp
print(y)
yield y
fig,ax = plt.subplots(figsize=(7,5))
def init():
global y
ax.clear()
y=[7,8,5,3,1,9,4,2,10,6]
plt.bar(x,y,color=['blue'])
def animX(i):
ax.clear()
plt.bar(x,y,color=['blue'])
return plt
anim = animation.FuncAnimation(fig,animX,frames=animator_X,interval=100,init_func=init)
plt.show()
launch binder
。当它出现时,您可以粘贴代码。
我怀疑在OP的代码中在
global y
函数中添加init()
行将修复OP的版本。
进一步说明
它确实不断重复OP中发布的代码,因为内核在第一次通过后继续在该单元上运行。
y
函数本地的
init
对象将在
init()
函数的范围内重置。我不太了解
FuncAnimation()
如何决定更新/以及它显示的内容,然后告诉你为什么OP代码没有更新主范围中的y会导致它显示
init()
状态并且不会闪烁到初始化状态,然后返回排序状态。内核仍在运行,所以也许它在这两者之间闪烁,但由于某种原因
init()
占主导地位?这是猜测,因为
FuncAnimation()
非常专业,它不会显示
print
内的
init
语句或动画化的 main 函数中的内容,因此以简单化的方式探索与情节分开的情况方式,并不容易。JupyterLab 和 Jupyter Notebook 7+ 更新
%matplotlib ipympl
import matplotlib.pyplot as plt
import matplotlib.animation as animation
x=["1","2","3","4","5","6","7","8","9","10"]
y=[7,8,5,3,1,9,4,2,10,6]
temp=0
def animator_X():
for a in range(len(y)-1):
for b in range(len(y)-a-1):
if y[b]>y[b+1]:
temp = y[b]
y[b]=y[b+1]
y[b+1]=temp
print(y)
yield y
fig,ax = plt.subplots(figsize=(7,5))
def init():
global y
ax.clear()
y=[7,8,5,3,1,9,4,2,10,6]
plt.bar(x,y,color=['blue'])
def animX(i):
ax.clear()
plt.bar(x,y,color=['blue'])
return plt
anim = animation.FuncAnimation(fig,animX,frames=animator_X,interval=100,init_func=init)
anim;
请注意,与我发布的原始版本相比,仅调整了开头和结尾,实际上只有从 %matplotlib notebook
到
%matplotlib ipympl
的更改才是关键。因为原始帖子是在 2022 年发布的,并且没有提及 JupyterLab,所以我认为涉及 Jupyter Notebook。以上所有内容都适用于 Jupyter Notebook 6.5 及更早版本(目前也应适用于 NbClassic;如果不清楚我为什么要提出版本号或这些术语是什么,请参阅我的答案的后半部分,其中引用了资源详细介绍了 Jupyter 生态系统在 2023 年如何发生巨大变化,Jupyter Notebook 7+ 是在与 JupyterLab 相同的组件上构建的
)。因此,我更新了这篇文章的结尾,将更新这篇文章的顶部,以提供有关如何将其与 JupyterLab 和 Jupyter Notebook 7+ 现在一起使用的更好指导。
您可以在 JupyterLab 中通过 MyBinder 提供的会话进行尝试,其中 ipympl
已经安装完毕,因此上述代码的所有内容都已设置完毕,只需转到此处并单击“直接开始链接”下的“
launch binder
”徽章即可在 JupyterLab 全功能模式下的笔记本模式中:'(或直接单击此处启动)。 (我现在没有提供使用 Jupyter Notebook 7+ 的良好环境。即使之前没有在会话中安装
ipympl
,也有可能,请参阅我的帖子的中间了解步骤让这样的会话正常工作。)