基于matplotlib.animation的动态绘图

基于matplotlib.animation的动态绘图方法

matplotlib是python中最基本,也是最常用的画图工具。利用matplotlib不仅可以绘制各种各样的图片,还可以制作一些小动画,下面就来介绍一下matplotlib如何制作动画。

动画的制作是基于matplotlib的animation,对于一条线的绘制,网上的教程很多,这里不介绍,主要介绍一下一图多线的情况。

# 导入相关库
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.animation as animation

# 生成数据
x1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
x2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y2 = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.10]

# 简单设置一下绘图基本参数
sns.set_style('darkgrid')

# 绘图
fig, ax = plt.subplots()
ax.set_title('draw lines')
ax.set_xlabel('x')
ax.set_ylabel('y')
ln1, =ax.plot([], [], 'r-o', animated=False)
ln2, =ax.plot([], [], 'r-o', animated=False)
ax.legend(['y1, y2'], loc='upper left')

def update(frame):
    x_1 = x1[0:frame]
    y_1 = x1[0:frame]
    x_2 = x1[0:frame]
    y_2 = x1[0:frame]
    ln1.set_data(x_1, y_1)
    ln2.set_data(x_2, y_2)
    return ln1, ln2,

ani = animation.FuncAnimation(fig, update, frames=len(x1)+1, interval=300, blit=True)

plt.show()

绘制的图像如下:

posted @   LittleTom123  阅读(31)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示