iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Pythonmatplotlib动画绘制详情
  • 890
分享到

Pythonmatplotlib动画绘制详情

2024-04-02 19:04:59 890人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

目录最最简单的操作Animation类FuncAnimationArtistAnimation动画保存.save()函数最最简单的操作 import numpy as np impo

最最简单的操作

import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.subplots()
 
x = np.linspace(0,10,100)
y = np.sin(x)
 
while True:
    ax.plot(x,y)
    plt.pause(1)
    ax.cla()      
    x += np.pi/30    
    y = np.sin(x)

有人会问,为什么不能直接 用 plot 替代 ax 呢?

好问题,你可以一试,会发现这玩意没法关掉 。。 当然  ctrl + C等暴力手段是任何时候都ok的

Animation类

FuncAnimation

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

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
fig = plt.figure()
ax = fig.subplots()
 
x = np.linspace(0,10,100)
y = np.sin(x)
ax.set_aspect(3)
ax.plot(x,y,'-.',c='red',label="the old one")
line = ax.plot(x,y,c='green')
plt.legend()
 
def fun(i):  
    global x    
    x += 0.1
    y = np.sin(x)
    line[0].set_ydata(y)
    return line
 
 
animation = FuncAnimation(fig,fun,interval=100) 
plt.show() 

这就有两个问题需要解决一下

第一个:line到底是什么类型的东西

type(line)
<class 'list'>

明显,这就是。。列表。

第二个:set_data;set_xdata;set_ydata

你可以自己更改一下试试看,结果是显而易见的

ArtistAnimation

它的好处是你不要费尽心机去想一个可能 勾八 的函数了

它的坏处是 :

一个能用函数表示的动画 为什么要在新增一个列表才能表达呢?

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import ArtistAnimation
fig = plt.figure()
ax = fig.subplots()
 
frames = []
x = np.linspace(0,np.pi*2,10)
for i in range(20):
    x += np.pi*2/20
    y = np.sin(x)
    frames.append(ax.plot(y,'-.',c='red'))
 
animation = ArtistAnimation(fig,frames,interval=100)
plt.show() 

很好!现在只需要保存动画就圆满了

动画保存

.save()函数

filename画文件名+后缀
fps动画每秒的帧数   默认值为 原动画的帧数
dpi动画每英寸的点数 默认值为 原动画的点数
codec编码格式 默认值为’h264’

filename画文件名+后缀fps动画每秒的帧数   默认值为 原动画的帧数dpi动画每英寸的点数 默认值为 原动画的点数codec编码格式 默认值为’h264’

animation.save("1.gif")

到此这篇关于python matplotlib 动画绘制的文章就介绍到这了,更多相关Python matplotlib 内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: Pythonmatplotlib动画绘制详情

本文链接: https://www.lsjlt.com/news/120287.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作