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")
数据集示例
| Month | Role | Year | Count |
|---|---|---|---|
| January | Officer | 2019 | 3 |
| January | Security | 2020 | 2 |
| February | Staff | 2021 | 4 |
| March | Faculty | 2022 | 1 |
问题原因
问题出在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
相关产品推荐
相关产品推荐

