如何在Python中基于图片创建路径动画折线图?
实现锚点间的顺序动画连线(基于Matplotlib)
你可以用Matplotlib的FuncAnimation模块实现锚点间的顺序动画连线,同时统计员工返回手推车的次数。以下是修改后的完整代码,包含动画逻辑和次数统计:
from matplotlib import image from matplotlib import pyplot as plt import numpy as np from matplotlib.animation import FuncAnimation # 读取图片 data = image.imread('Asset 1.png') # 锚点坐标(索引0对应手推车) plots = np.array([[500,200], #trolley (index 0) [420,200], #bath/shower (1) [370,45], #wardrobe (2) [370,320], #sink (3) [320,250], #toilet (4) [280,45], #fridge/coffee (5) [175,40], #desk (6) [180,150], #bed (7) [250,220], #bedside table 1 (8) [110,220], #bedside table 2 (9) [40,150], #table (10) [20,100], #window/curtains (11) [65,190], #chair (12) [75,75]]) #carpet (13) # 自定义行动路径的锚点索引顺序(按需求调整) # 示例:手推车→浴室→床→手推车→洗手池→马桶→手推车 path_indices = [0, 1, 7, 0, 3, 4, 0] # 初始化画布和轴 fig, ax = plt.subplots() plt.imshow(data) plt.scatter(plots[:,0], plots[:,1], marker='o', color="red") # 创建空线条用于绘制路径 line, = ax.plot([], [], color='blue', linewidth=2) # 显示返回手推车的次数文本 count_text = ax.text(10, 30, '返回手推车次数: 0', color='white', fontsize=12) # 初始化路径数据和计数 current_path_x = [] current_path_y = [] return_count = 0 def update(frame): global current_path_x, current_path_y, return_count # 获取当前步骤的起始和目标锚点 start_idx = path_indices[frame] end_idx = path_indices[frame+1] # 添加当前路径段的坐标 current_path_x.extend([plots[start_idx,0], plots[end_idx,0]]) current_path_y.extend([plots[start_idx,1], plots[end_idx,1]]) # 更新线条数据 line.set_data(current_path_x, current_path_y) # 如果目标锚点是手推车,计数+1并更新文本 if end_idx == 0: return_count += 1 count_text.set_text(f'返回手推车次数: {return_count}') return line, count_text # 创建动画:frames为路径段数量,interval控制每段动画间隔(毫秒) ani = FuncAnimation(fig, update, frames=len(path_indices)-1, interval=1000, blit=True) # 保存动画为GIF(需先安装pillow库:`pip install pillow`) # ani.save('staff_path_animation.gif', writer='pillow') plt.show()
关键说明:
- 路径定义:
path_indices是自定义的行动顺序,每个数字对应plots中的锚点索引,比如0代表手推车,可完全按需求调整顺序。 - 动画更新逻辑:
update函数每帧绘制一段路径,同时检查是否回到手推车,实时更新返回次数。 - 动画控制:
interval参数控制每段路径的显示间隔,数值越小动画播放速度越快。 - 保存动画:取消注释
ani.save行可将动画保存为GIF文件,需要提前执行pip install pillow安装依赖库。
你可以根据客户需求调整路径顺序、线条样式、计数文本位置等,适配展示场景。
内容的提问来源于stack exchange,提问作者FboroSaint21
相关产品推荐
相关产品推荐

