可以使用 FuncAnimation 函数来实现折线图的缓慢上涨或下跌的动画效果。具体步骤如下:

  1. 导入 FuncAnimation 和 rcParams 模块。

  2. 设置 rcParams 中的动画参数,例如动画帧率、动画持续时间等。

  3. 编写 update 函数,用于更新折线图的数据和背景图片。

  4. 调用 FuncAnimation 函数,传入 figure、update 函数、帧数和重复标志等参数,生成动画效果。

下面是修改后的代码:

import matplotlib.pyplot as plt
from PIL import Image
import random
from matplotlib.animation import FuncAnimation
from matplotlib import rcParams

# 设置动画参数
rcParams['animation.html'] = 'jshtml'
rcParams['animation.fps'] = 10
rcParams['animation.duration'] = 2000

# 随机选择一张图片作为背景
bg_list = ['bg1.jpg', 'bg2.jpg', 'bg3.jpg']
bg_img = Image.open(random.choice(bg_list))

# 模拟数据
years = [2015, 2016, 2018, 2019, 2020]
visitors = [105500, 1200000, 1400000, 1600000, 1800000]

# 创建画布和子图对象
fig, ax = plt.subplots()

# 绘制初始折线图和背景图片
line, = ax.plot(years, visitors, marker='o')
im = ax.imshow(bg_img, extent=[years[0], years[-1], visitors[0], visitors[-1]], aspect='auto', alpha=0.5)

# 设置图形标题和坐标轴标签
plt.title('大唐')
plt.xlabel('年')
plt.ylabel('万人')

# 编写update函数
def update(frame):
    # 生成新的模拟数据
    new_visitors = [v + random.randint(-5000, 5000) for v in visitors]
    # 更新折线图和背景图片
    line.set_ydata(new_visitors)
    im.set_data(bg_img)
    # 返回更新后的子图对象
    return [line, im]

# 调用FuncAnimation函数生成动画效果
ani = FuncAnimation(fig, update, frames=range(10), repeat=True)

# 显示动画效果
plt.show()

代码解析:

  1. 导入必要模块: 导入 matplotlib.pyplot 用于绘图,PIL 用于处理图片,random 用于生成随机数据,matplotlib.animation.FuncAnimation 用于创建动画,matplotlib.rcParams 用于设置动画参数。
  2. 设置动画参数: 使用 rcParams 设置动画参数,包括 animation.html、animation.fps 和 animation.duration。animation.html 用于指定动画的输出格式,animation.fps 用于设置动画帧率,animation.duration 用于设置动画持续时间。
  3. 准备数据和背景图片: 随机选择一张图片作为背景,模拟数据,创建画布和子图对象。
  4. 绘制初始图形: 绘制初始折线图和背景图片。
  5. 编写更新函数 update: update 函数用于更新每一帧的图形数据。在这个例子中,update 函数会生成新的模拟数据,并更新折线图和背景图片的数据。
  6. 创建动画: 使用 FuncAnimation 函数创建动画。FuncAnimation 函数接受 figure、update 函数、帧数和重复标志等参数。帧数指定动画的总帧数,重复标志指定动画是否重复播放。
  7. 显示动画: 使用 plt.show() 显示动画。

注意: 需要安装 Pillow 库来处理图片。使用 pip install Pillow 安装该库。

代码示例: 代码会生成一个动画折线图,其中折线会缓慢上涨或下跌,背景图片也会随之变化。你可以根据需要调整动画参数和模拟数据,创建不同的动画效果。

Python Matplotlib 折线图动画:缓慢上涨或下跌效果

原文地址: https://www.cveoy.top/t/topic/oc2K 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录