Python Matplotlib 折线图动画:缓慢上涨或下跌效果
可以使用 FuncAnimation 函数来实现折线图的缓慢上涨或下跌的动画效果。具体步骤如下:
-
导入
FuncAnimation和rcParams模块。 -
设置
rcParams中的动画参数,例如动画帧率、动画持续时间等。 -
编写
update函数,用于更新折线图的数据和背景图片。 -
调用
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()
代码解析:
- 导入必要模块: 导入
matplotlib.pyplot用于绘图,PIL用于处理图片,random用于生成随机数据,matplotlib.animation.FuncAnimation用于创建动画,matplotlib.rcParams用于设置动画参数。 - 设置动画参数: 使用
rcParams设置动画参数,包括animation.html、animation.fps和animation.duration。animation.html用于指定动画的输出格式,animation.fps用于设置动画帧率,animation.duration用于设置动画持续时间。 - 准备数据和背景图片: 随机选择一张图片作为背景,模拟数据,创建画布和子图对象。
- 绘制初始图形: 绘制初始折线图和背景图片。
- 编写更新函数
update:update函数用于更新每一帧的图形数据。在这个例子中,update函数会生成新的模拟数据,并更新折线图和背景图片的数据。 - 创建动画: 使用
FuncAnimation函数创建动画。FuncAnimation函数接受figure、update函数、帧数和重复标志等参数。帧数指定动画的总帧数,重复标志指定动画是否重复播放。 - 显示动画: 使用
plt.show()显示动画。
注意: 需要安装 Pillow 库来处理图片。使用 pip install Pillow 安装该库。
代码示例: 代码会生成一个动画折线图,其中折线会缓慢上涨或下跌,背景图片也会随之变化。你可以根据需要调整动画参数和模拟数据,创建不同的动画效果。
原文地址: https://www.cveoy.top/t/topic/oc2K 著作权归作者所有。请勿转载和采集!