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

Python matplotlib散点图如何为对应数据点添加Name列标注

散点图添加Name列文本标注实现方案

你只需要在生成散点图的轴对象之后,遍历DataFrame的每一行,调用轴对象的text()方法,把对应Name文本绘制到点的坐标位置即可,建议给坐标加微小偏移,避免文本直接覆盖散点标记。

核心修改点

在现有代码sp = df.plot.scatter(...)代码块之后,plt.show()之前,添加遍历标注的代码即可:

# 遍历所有数据行,给每个点加文本标注
for _, row in df.iterrows():
    # 前两个参数是标注的x、y坐标,x加0.05、y加0.01的偏移避免遮挡散点
    sp.text(
        x=row["Gls"] + 0.05,
        y=row["xG"] + 0.01,
        s=row["Name"],
        fontsize=9 # 可根据图表尺寸调整字号
    )

调整后的完整可运行代码

import pandas as pd
import matplotlib.pyplot as plt


df = pd.read_csv("moneynuts.csv", index_col=0)
columns = df.columns

def clean_stringy_number(num: str) -> str:
    
    if num == "-":
        return "0"

    num = num.replace(",", "")

    return num


df.dropna(subset=['Gls'], inplace=True)

df.dropna(subset=['xG'], inplace=True)

df["Gls"] = df["Gls"].apply(clean_stringy_number)   

df["Gls"] = df["Gls"].apply(int)
df["xG"] = df["xG"].apply(clean_stringy_number)
df["xG"] = df["xG"].apply(float)

for index, row in df.iterrows():
    if (row["Gls"] == "-" or row["Gls"] == "0"):
        if (row["xG"] == "-" or row["xG"] == "0"):
            continue
        continue
    print (row["Name"], " average goals of ", row["Gls"], " With an xG of ", row["xG"])
    
    
    try:
        gls = float(row["Gls"].replace(",", "."))
        xG = float(row["xG"].replace(",", "."))
    except:
        print("Unknown char")


df["xG"] = df["xG"] / 100


sp = df.plot.scatter(x='Gls',
                     y='xG')
x_values = df["Gls"].astype(int)
plt.xticks(range(x_values.min(), x_values.max()+1))

# 新增:添加每个点的Name标注
for _, row in df.iterrows():
    sp.text(row["Gls"] + 0.05, row["xG"] + 0.01, row["Name"], fontsize=9)

plt.show()

可选优化项

  • 文本重叠处理:如果点比较密集出现文字遮挡,可调整text()里的x/y偏移量,也可使用adjustText库实现自动文本避让,示例代码:
    from adjustText import adjust_text
    texts = []
    for _, row in df.iterrows():
        texts.append(sp.text(row["Gls"], row["xG"], row["Name"], fontsize=9))
    # 自动调整文字位置,加灰色指向箭头关联对应散点
    adjust_text(texts, arrowprops=dict(arrowstyle='->', color='gray'))
    
  • 样式调整:可通过fontsize、color、alpha等参数修改标注文字的字号、颜色、透明度,匹配整体图表风格。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 01:42:17