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

如何使用CSV数据中的player列为matplotlib图表的数据点添加文本标签

解决方案

核心修正点如下:

  • 修正x、y数据的取值错误,匹配你需求的x=pass_att、y=pass_cmp
  • 正确提取player列的球员名称列表
  • 遍历每一个数据点,调用annotate方法逐个添加文本标签

以下是可直接运行的修正后代码:

import pandas as pd
import matplotlib.pyplot as plt

nfl_df = pd.read_csv('nfl2.csv') 
nfl_df = nfl_df.sort_values(by ='pass_att', ascending = False)

# 直接通过列名提取对应数据,避免索引取值错误
x_2 = nfl_df['pass_att']
y_2 = nfl_df['pass_cmp']
player_names = nfl_df['player']

fig_4 = plt.figure(figsize = (10,6))
# 原add_axes参数超出画布显示范围,修正为0-1区间的相对比例值
axes_4 = fig_4.add_axes([0.1,0.1,0.8,0.8])

axes_4.set_xlabel('Pass Att')
axes_4.set_ylabel('Pass Cmp')
axes_4.set_title('Pass Att vs Pass Cmp')
axes_4.plot(x_2,y_2, color='cyan', alpha = .90, lw = 2, ls = '-.', marker = 'o', markersize = 7, markerfacecolor = 'b')

# 遍历每个数据点添加标签,xytext参数可调整标签与点的偏移距离,避免遮挡
for x, y, name in zip(x_2, y_2, player_names):
    axes_4.annotate(name, xy=(x, y), xytext=(5, 3), textcoords='offset points')

plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 16:06:04