You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何结合Plotly动画散点图实现PNG图片替换数据点?

问题:实现多周数据的图片散点动画展示

我有一个按周划分的dmg DataFrame数据集,每条记录包含对应PNG图片路径,示例数据如下:

wwtypepawnimgpicwr
2022-08-08dmgCrypath1.png3-9
2022-08-08dmgRopath5.png1-11
2022-08-08dmgDempath4.png31-5
2022-08-08dmgMagpath3.png0-36
2022-08-08dmgReapath2.png1-6
2022-08-15dmgCrypath1.png69
2022-08-15dmgRopath5.png5-1
2022-08-15dmgDempath4.png230
2022-08-15dmgMagpath3.png5-5
2022-08-15dmgReapath2.png1922

针对单周数据,我可以用以下代码实现图片替代散点的图表:

from PIL import Image
import plotly.graph_objects as go

fig = go.Figure()
for i, x in enumerate(dmg['pic']):
    fig.add_layout_image(
            dict(
                source=Image.open(dmg['img'].iloc[i]),
                xref="x",
                yref="y",
                x=x,
                y=dmg['wr'].iloc[i],
                sizex=2,
                sizey=2
            )
    )
fig.update_layout(xaxis_range=[0, 100], yaxis_range=[-20,20])

fig.show()

我尝试用以下代码创建多周动画框架,但不知道如何将两段代码结合,在每个动画帧中加载对应PNG图片并更新布局:

import plotly.express as px

fig = px.scatter(dmg, x='pic', y='wr', animation_frame="ww")

请问如何实现将图片替代散点的逻辑融入多周动画中?


解决方案

要实现每个动画帧加载对应周的图片散点,需要手动构建每个帧的布局图片,结合Plotly的动画帧配置来实现,步骤如下:

1. 导入依赖库

确保导入所需工具库:

from PIL import Image
import plotly.graph_objects as go
import pandas as pd

2. 按周分组构建动画帧

将数据集按周分组,为每个周单独生成图片布局配置:

# 按周分组处理数据
weekly_groups = dmg.groupby('ww')
frames = []

# 遍历每个周的数据集,生成对应动画帧
for week, group in weekly_groups:
    # 收集当前周所有图片的布局配置
    current_images = []
    for _, row in group.iterrows():
        img_config = dict(
            source=Image.open(row['img']),
            xref="x",
            yref="y",
            x=row['pic'],
            y=row['wr'],
            sizex=2,
            sizey=2,
            xanchor="center",  # 图片中心对齐坐标点
            yanchor="middle"
        )
        current_images.append(img_config)
    
    # 创建当前周的动画帧
    frame = go.Frame(
        layout=go.Layout(
            images=current_images,
            title=f"周数据:{week}"
        )
    )
    frames.append(frame)

3. 初始化基础图表与交互控件

创建空图表容器,设置坐标轴范围和播放/暂停控件:

fig = go.Figure(
    data=[],  # 无需基础散点数据,仅用图片布局
    frames=frames,
    layout=go.Layout(
        xaxis=dict(range=[0, 100], title='pic'),
        yaxis=dict(range=[-40, 30], title='wr'),  # 扩大范围适配所有周数据
        updatemenus=[dict(
            type="buttons",
            buttons=[dict(
                label="播放",
                method="animate",
                args=[None, dict(
                    frame=dict(duration=1000, redraw=True),
                    transition=dict(duration=500),
                    fromcurrent=True
                )]
            ), dict(
                label="暂停",
                method="animate",
                args=[[None], dict(
                    frame=dict(duration=0, redraw=False),
                    mode="immediate",
                    transition=dict(duration=0)
                )]
            )]
        )]
    )
)

# 设置初始显示第一周的数据
first_week = list(weekly_groups.groups.keys())[0]
fig.update_layout(images=frames[0].layout.images, title=f"周数据:{first_week}")

4. 展示动画

fig.show()

关键说明

  • 每个动画帧独立维护一组图片布局,切换帧时会完全替换当前显示的图片
  • xanchor和yanchor参数确保图片中心与坐标点对齐,避免偏移
  • 坐标轴范围需覆盖所有周的数据,防止图片超出可视区域
  • 通过updatemenus添加播放/暂停按钮,提升交互体验

内容的提问来源于stack exchange,提问作者Dauren Sergazin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 02:45:35