Plotly散点图仅显示每日首个数据点,其余仅可悬停问题解决
解决Plotly动画散点图仅显示每日每个国家首个数据点的问题
问题原因
使用animation_group="country"时,Plotly会将同一国家在同一日期(animation_frame="datetime_str")下的所有小时数据点视为同一实体的不同状态,因此仅保留一个点用于动画过渡逻辑,其余点被隐藏(仅悬停时可见)。
解决方案
方案一:创建唯一标识每个小时数据点的分组字段
在绘图前为DataFrame添加一个结合国家和小时的唯一字段,让每个国家的每个小时点都被视为独立动画实体:
# 添加唯一分组字段 plot_df['country_hour'] = plot_df['country'] + '_' + plot_df['datetime'].dt.strftime('%H') # 修改绘图代码 fig = px.scatter(plot_df, x="value1", y="value2", animation_frame="datetime_str", animation_group="country_hour", color="country", hover_name="country") fig.show()
方案二:移除animation_group参数
如果不需要跨动画帧的实体跟踪过渡效果,直接删除animation_group参数,Plotly会在每个帧中加载对应日期的所有小时数据点:
fig = px.scatter(plot_df, x="value1", y="value2", animation_frame="datetime_str", color="country", hover_name="country") fig.show()
内容的提问来源于stack exchange,提问作者yarvis
相关产品推荐
相关产品推荐

