检查这段代码中的错误部分并改正import matplotlibpyplot as pltfrom PIL import Imageimport randomfrom matplotlibanimation import FuncAnimationfrom matplotlib import rcParams# 设置动画参数rcParamsanimationhtml = jshtmlrcParam
将rcParams['animation.html']改为rcParams['animation.writer'],将rcParams['animation.duration']改为rcParams['animation.interval'],并将im.set_data(bg_img)改为im.set_data(bg_img.convert('RGBA'))。
修改后的代码如下:
import matplotlib.pyplot as plt from PIL import Image import random from matplotlib.animation import FuncAnimation from matplotlib import rcParams
设置动画参数
rcParams['animation.writer'] = 'jshtml' rcParams['animation.fps'] = 10 rcParams['animation.interval'] = 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.convert('RGBA'), 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.convert('RGBA')) # 返回更新后的子图对象 return [line, im]
调用FuncAnimation函数生成动画效果
ani = FuncAnimation(fig, update, frames=range(10), repeat=True)
显示动画效果
plt.show(
原文地址: http://www.cveoy.top/t/topic/fmIE 著作权归作者所有。请勿转载和采集!