《深入浅出Matplotlib Animation》

一、Matplotlib Animation简介

Matplotlib是Python中常用的绘图库。其官方提供的animation模块是利用FuncAnimation实现动画效果的核心模块。animation模块中包含Animation类和FuncAnimation类,后者是Animation的一个子类。FuncAnimation提供了一种基于帧的动画的方法,即通过更新数据并绘制图像来实现动态图的效果。

在实际应用过程中,动态图能比静态图更直观地展示数据的变化,如在时间序列分析或仿真过程中,可以利用动态图很好地展示数据变化的过程。同时,动态图也根据用户的需求可以自定义视图和交互方式。

以下是简单示例代码:

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

def update_line(num, data, line):
    line.set_data(data[..., :num])
    return line,
    
fig, ax = plt.subplots()

data = np.random.rand(2, 25)
line, = ax.plot(data[0, 0:1], data[1, 0:1])

ani = animation.FuncAnimation(fig, update_line, frames=25, fargs=(data, line), 
                              interval=50, blit=True)

plt.show()

二、Matplotlib动画模块常用可视化效果

1.基本图形渲染

Matplotlib动画可以实现基本图形渲染,如折线图、散点图等。基本图形渲染的数据更新通过update函数实现,每次update函数被调用时,图形的渲染结果被重新绘制并显示在界面中。

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as ani

x = np.linspace(0, 2*np.pi, 200)
y = np.sin(x)
fig, ax = plt.subplots()
line, = ax.plot(x, y)

def update(num):
    line.set_ydata(np.sin(x+num))
    return line,

ani = ani.FuncAnimation(fig, update, frames=10, interval=200)
plt.show()

2.多个图形渲染

动画模块还可以实现多个图形的渲染,例如同时绘制折线图和直方图。

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as ani

fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(10, 5))

x = np.linspace(0, 10, num=100)
y = np.sin(x)

line, = ax1.plot([], [], lw=2)
ax1.set_xlim(0, 10), ax1.set_ylim(-1, 1)

rects = ax2.bar([], [])

def init():
    line.set_data([], [])
    rects.set_height(10)
    return line, rects

def animate(i):
    line.set_data(x[:i], y[:i])
    data = np.random.rand(10)
    rects.set_height(data)
    rects.set_color('r')
    return line, rects

anim = ani.FuncAnimation(fig, animate, init_func=init, frames=100, 
                         interval=100, blit=True)
plt.show()

三、Matplotlib动画模块常见案例

1.简单的心电图动态效果

在健康检查或医学研究中,心电图是一种常用的监控方式。

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

fig = plt.figure()
data = np.random.normal(0, 1, (1000, 1)).cumsum(0)

def update(i):
    plt.cla()
    plt.plot(data[:i])
    plt.ylim(-50, 50)
    plt.yticks(np.arange(-50, 50, 10))
    plt.grid(True)

ani = animation.FuncAnimation(fig, update, frames=len(data), interval=50)
plt.show()

2.简单粒子演示效果

演示效果是指在动画中绘制一系列的对象,其中每个对象都是在动画中相对于另一个对象变化的。一种公共的演示效果是沙粒演示,其中颗粒在动画中随机地移动和相互运动,这些效果模拟了许多真实世界物理系统的动态。

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

n_particles = 50
n_steps = 50

rx = np.random.uniform(-1, 1, n_particles)
ry = np.random.uniform(-1, 1, n_particles)
velx = np.random.normal(0, 0.1, n_particles)
vely = np.random.normal(0, 0.1, n_particles)

fig, ax = plt.subplots()

scat, = ax.plot([], [], ".")

def update(t, rx, ry, velx, vely):
    rx = (rx + velx) % 1.0
    ry = (ry + vely) % 1.0

    scat.set_data(rx, ry)
    return scat,

ani = animation.FuncAnimation(fig, update, frames=n_steps, fargs=(rx, ry, velx, vely),
                              interval=50, blit=True)

plt.show()

3.简单的飞行器动画

该动画基于二维流体力学的概念,演示了一个以匀速飞行的飞机离开起飞场。

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

fig, ax = plt.subplots()

M = 100
x = np.cumsum(np.random.randn(M))
y = np.cumsum(np.random.randn(M))

im = ax.imshow(np.zeros((100, 100)), vmin=-1, vmax=1)

def update(j):
    im.set_data(np.random.randn(100, 100))
    im.set_extent([x[j]-50, x[j]+50, y[j]-50, y[j]+50])
    return im

ani = animation.FuncAnimation(fig, update, frames=M, interval=50)

plt.show()

原创文章,作者:FODUF,如若转载,请注明出处:https://www.506064.com/n/363911.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
FODUFFODUF
上一篇 2025-03-12 18:48
下一篇 2025-03-15 09:22

相关推荐

  • Python最强大的制图库——Matplotlib

    Matplotlib是Python中最强大的数据可视化工具之一,它提供了海量的制图、绘图、绘制动画的功能,通过它可以轻松地展示数据的分布、比较和趋势。下面将从多个方面对Matplo…

    编程 2025-04-29
  • Python三大:NumPy、Pandas、matplotlib

    本文将详细介绍三大Python数据处理及可视化库——NumPy、Pandas以及matplotlib,为读者提供从基础使用到应用场景的全面掌握。 一、NumPy NumPy是Pyt…

    编程 2025-04-27
  • Python画图:Matplotlib的使用

    Matplotlib是Python中最常用的画图库之一。它可以轻松地创建各种类型的图表,包括直方图、散点图、线图、饼图等等。本文将从以下几个方面对Matplotlib的使用进行详细…

    编程 2025-04-27
  • 深入浅出统计学

    统计学是一门关于收集、分析、解释和呈现数据的学科。它在各行各业都有广泛应用,包括社会科学、医学、自然科学、商业、经济学、政治学等等。深入浅出统计学是指想要学习统计学的人能够理解统计…

    编程 2025-04-25
  • 深入浅出torch.autograd

    一、介绍autograd torch.autograd 模块是 PyTorch 中的自动微分引擎。它支持任意数量的计算图,可以自动执行前向传递、后向传递和计算梯度,同时提供很多有用…

    编程 2025-04-24
  • 深入浅出SQL占位符

    一、什么是SQL占位符 SQL占位符是一种占用SQL语句中某些值的标记或占位符。当执行SQL时,将使用该标记替换为实际的值,并将这些值传递给查询。SQL占位符使查询更加安全,防止S…

    编程 2025-04-24
  • 深入浅出:理解nginx unknown directive

    一、概述 nginx是目前使用非常广泛的Web服务器之一,它可以运行在Linux、Windows等不同的操作系统平台上,支持高并发、高扩展性等特性。然而,在使用nginx时,有时候…

    编程 2025-04-24
  • 深入浅出ThinkPHP框架

    一、简介 ThinkPHP是一款开源的PHP框架,它遵循Apache2开源协议发布。ThinkPHP具有快速的开发速度、简便的使用方式、良好的扩展性和丰富的功能特性。它的核心思想是…

    编程 2025-04-24
  • 探究matplotlib中文文档

    一、介绍 Matplotlib是一个Python的可视化库,它提供了丰富的绘图工具和良好的交互性,可用于生成高质量的二维图形、三维图形和动画等。它的中文文档是对于使用者非常友好的参…

    编程 2025-04-24
  • 深入浅出arthas火焰图

    arthas是一个非常方便的Java诊断工具,包括很多功能,例如JVM诊断、应用诊断、Spring应用诊断等。arthas使诊断问题变得更加容易和准确,因此被广泛地使用。artha…

    编程 2025-04-24

发表回复

登录后才能评论