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

Plotly堆叠条形图动画帧年份数据匹配错误问题求助

问题:Plotly堆叠条形图动画hover数据与当前帧年份不匹配

使用Python的Plotly库制作带年份动画的堆叠条形图,拖动滚动条切换年份帧时,hover部分条形显示的数据年份与当前帧不一致(比如2022年帧的条形显示2020年的数据)。

用户代码

import pandas as pd
import matplotlib.pyplot as plt
import datetime
import plotly.graph_objects as go
import plotly.express as px

Role_counts = pd.read_csv('Role_counts.csv')

Role_counts = Role_counts.sort_values(by = ['Year'], ascending = [True], na_position = 'first')

fig2 = px.bar(Role_counts, x='Month', y='Count', color='Role', barmode='stack',
             animation_frame="Year",animation_group="Month",
              range_y=[0, 30], title = "Counts by Role")

数据集示例

MonthRoleYearCount
JanuaryOfficer20193
JanuarySecurity20202
FebruaryStaff20214
MarchFaculty20221

问题原因

问题出在animation_group="Month"参数上:

  • Plotly的animation_group用于定义跨动画帧保持关联的分组键
  • 仅按Month分组时,不同年份的同一个月会被归为同一组,导致动画切换时,hover信息错误关联到同组内其他年份的记录

解决方案

将animation_group设置为Month和Role的组合键,确保每个分组对应唯一的(Month, Role)组合,这样Plotly就能正确匹配当前帧年份下的对应数据。

修改后的完整代码

import pandas as pd
import plotly.express as px

Role_counts = pd.read_csv('Role_counts.csv')
Role_counts = Role_counts.sort_values(by=['Year'], ascending=[True], na_position='first')

# 用Month+Role作为动画分组键,确保数据唯一对应
fig2 = px.bar(Role_counts, x='Month', y='Count', color='Role', barmode='stack',
             animation_frame="Year", animation_group=["Month", "Role"],
              range_y=[0, 30], title="Counts by Role")
fig2.show()

原理说明

每个数据点的唯一标识是Month+Role+Year,通过将animation_group设置为["Month", "Role"],Plotly会为每个(Month, Role)组合创建独立的分组,动画切换年份帧时,hover信息只会加载当前年份下该分组的对应数据,避免跨年份的数据混淆。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 01:55:19