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

matplotlib绘制散点图无法为首尾数据点添加标签求助

核心问题

标签无法正常添加/报错的根源有两处:

  1. 你在执行排序操作前就提前把happy/satis/country列单独赋值为变量,后续sort_values仅修改了原DataFrame的行顺序,提前提取的三个变量仍保留原始乱序,和排序后的数据完全错位。
  2. 未调用Matplotlib的文本标注接口,标签自然不会渲染到图上。
可直接运行的修正代码

把你原有代码替换为如下版本即可,标注逻辑已经补全:

import pandas as pd
import numpy as np
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt

data = pd.read_csv('happy_income1.csv')

# 先排序,再提取绘图用列,保证顺序一致
data.sort_values('avg_satisfaction', inplace=True)
happy = data['happyScore']
satis = data['avg_satisfaction']
country = data['country']

# Zapping 2 arrays together
satis_happy = np.column_stack((satis,happy))

# Filtering
satisfied = data[data['avg_satisfaction']>4]
print(satisfied)

# Making clusters as required
# 补充n_init参数消除sklearn版本警告
k_res = KMeans(n_clusters=3, n_init=10).fit(satis_happy)
cluster = k_res.cluster_centers_
print(cluster)

# Plotting
fig, week4 = plt.subplots(figsize=(10,6))
week4.scatter(x=happy, y=satis, alpha=0.6)
week4.scatter(x=cluster[:,0], y=cluster[:,1], s=9999, alpha=0.25, c='crimson')
week4.set_xlabel('Happiness')
week4.set_ylabel('Satisfaction')
week4.set_title('Happiness versus Satisfaction')

# Labelling
# ----------------------------------------------
# 标注满意度最低的首个点
lowest_satis = data.iloc[0]
week4.annotate(
    text=lowest_satis['country'],
    xy=(lowest_satis['happyScore'], lowest_satis['avg_satisfaction']),
    xytext=(6,6), # 标签相对点偏移6像素,避免遮挡
    textcoords='offset points',
    fontsize=10
)
# 标注满意度最高的末尾点
highest_satis = data.iloc[-1]
week4.annotate(
    text=highest_satis['country'],
    xy=(highest_satis['happyScore'], highest_satis['avg_satisfaction']),
    xytext=(6,6),
    textcoords='offset points',
    fontsize=10
)
# ----------------------------------------------

plt.tight_layout()
plt.show()
改动说明
  • 调整了列提取的顺序,所有绘图用数据都在排序完成后再读取,彻底解决索引错位问题。
  • 用iloc[0]、iloc[-1]直接从排序后的DataFrame取首尾目标点,不需要额外维护索引映射。
  • 用annotate接口添加标签,通过偏移参数避免文字覆盖散点,可读性更好。
  • 补充KMeans的n_init参数,兼容新版scikit-learn,消除运行警告。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 06:48:22