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

Python中Plotly动画散点图仅显示指定球员文本的实现方法

仅在Plotly动画散点图中显示指定球员的名称

需求说明

现有包含足球球员数据的Pandas DataFrame,字段包括player_stat_x、player_stat_y、player_names、player_year。需要制作以player_year为动画帧的散点图,仅在动画过程中显示player_A的名称,其他球员不显示文本标签。

实现方案

核心思路是创建一个仅包含目标球员名称的文本列,其他行留空,将该列传给Plotly的text参数即可。同时建议将统计值转为数值类型,避免绘图异常;还可通过样式自定义突出目标球员,更便于跟踪。

完整代码示例

import pandas as pd
import plotly.express as px
import numpy as np

# 构造示例数据
d = {'player_names': ['player_A','player_A', 'player_B', 'player_B','player_C','player_C'],
     'player_stat_x': ['10', '15', '5', '8', '7', '9'],
     'player_stat_y':['1', '3', '2', '1', '4', '4'], 
     'player_year': ['2003', '2004','2003', '2004','2003', '2004']}
df = pd.DataFrame(data=d)

# 1. 将统计值转为数值类型(原数据是字符串,避免绘图错误)
df['player_stat_x'] = df['player_stat_x'].astype(int)
df['player_stat_y'] = df['player_stat_y'].astype(int)

# 2. 创建仅显示player_A名称的文本列
df['display_text'] = np.where(df['player_names'] == 'player_A', df['player_names'], '')

# 3. 绘制动画散点图
fig = px.scatter(df.sort_values(['player_year']), 
                 x="player_stat_x", 
                 y="player_stat_y",
                 animation_frame="player_year",
                 text="display_text",
                 # 可选:自定义player_A的颜色,突出显示
                 color=np.where(df['player_names'] == 'player_A', '目标球员', '其他球员'),
                 color_discrete_map={'目标球员': 'red', '其他球员': 'gray'}
                 )

# 调整文本标签位置,避免遮挡数据点
fig.update_traces(textposition='top center')

fig.show()

关键说明

  • np.where(df['player_names'] == 'player_A', df['player_names'], ''):仅当球员是player_A时填充名称,其余行设为空字符串,这样Plotly只会渲染player_A的文本标签。
  • 转换统计值为数值类型:原示例中player_stat_x和player_stat_y是字符串格式,Plotly绘制散点图时会按分类轴处理,转为数值型后才能正确展示连续的坐标变化。
  • 自定义颜色:通过color参数区分目标球员和其他球员,让player_A的轨迹更醒目,便于跟踪其每年的位置变化。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 15:30:56