解决方案:python FuncAnimation 无法显示动画

版权声明:如需转载或引用,请注明出处。 https://blog.csdn.net/weixin_39278265/article/details/84060864

前言

今天早上花了半个小时研究了一下FuncAnimation这个函数,在此记录。

环境

Spyder
Win10

问题

我的代码:

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np

fig,ax=plt.subplots()

a=[1,2,3,1,6,9,4,6,21,41,12]
b=[2,4,1,6,9,5,7,0,3,5,2]

xdata, ydata=[], []

ln, = ax.plot([], [])

def init():
    ax.set_xlim(1,45)
    ax.set_ylim(0,10)
    return ln,

def updata(i):
    i=int(i)
    xdata.append(a[i])
    ydata.append(b[i])
    ln.set_data(xdata,ydata)
    return ln,
    
ani =FuncAnimation(fig, updata,frames=np.linspace(0,10,11),init_func=init,blit=True)
plt.show()

在spyder中运行,输出:
在这里插入图片描述

解决方案

我猜测:
这是因为在控制台中,是没法显示动图的。
我应该把图形绘制放到控制台(console)外面,即放到独立窗口中。

设置如下:
最上方菜单栏Tools -> Preference -> IPython Console -> Graphics,将Backend处的Inline设置成Qt5.
点击OK
在这里插入图片描述

然后最上方菜单栏Consoles -> Restart kernel(即,重启一下控制台)

这时候再运行同样的代码,就可以显示动画了。

在这里插入图片描述

其他

在此过程中参考了一些FuncAnimation 的资料 (如FuncAnimation 函数的参数) [1-4]

这里就不赘述了。

参考文献

[1] matalb中的linspace是什么意思. https://zhidao.baidu.com/question/341021528.html

[2] Python使用matplotlib绘制动画的方法. https://www.jb51.net/article/66441.htm

[3] python学习之matplotlib绘制动图(FuncAnimation()参数). http://www.cnblogs.com/zhouzhe-blog/p/9614360.html

[4] 让数据动起来!用python制作动画可视化效果,让数据不再枯燥! http://m.sohu.com/a/231286709_99992472

猜你喜欢

转载自blog.csdn.net/weixin_39278265/article/details/84060864