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

如何用Matplotlib PyPlot按值范围为散点着色并自动标注

按值范围自动着色散点并标注球员的实现方案

直接用布尔索引筛选符合条件的行就行,不用手动挑单行。下面给你完整的可运行代码,一步步来:

核心步骤

  • 用df[(df['BLK'] > 1.5) & (df['BLK'] < 3)]筛选出盖帽数在1.5到3之间的球员数据
  • 先绘制所有球员的基础散点(可选,用来做对比背景)
  • 单独绘制筛选后的高亮散点,指定颜色
  • 循环遍历筛选后的行,用plt.annotate批量标注球员名

完整代码示例

import pandas as pd
import matplotlib.pyplot as plt

# 模拟你的球员数据(替换成你自己的DataFrame)
data = {
    'Player': ['SGA', 'Wemby', 'Giannis', 'Luka', 'LeBron'],
    'PTS': [28.5, 21.3, 32.1, 30.0, 25.8],
    'BLK': [0.8, 2.2, 1.7, 0.5, 0.6]
}
df = pd.DataFrame(data)

plt.figure(figsize=(10, 6))

# 1. 绘制所有球员的基础散点(灰色,作为背景)
plt.scatter(df['PTS'], df['BLK'], color='#cccccc', label='其他球员')

# 2. 筛选符合BLK范围的球员
filtered_df = df[(df['BLK'] > 1.5) & (df['BLK'] < 3)]

# 3. 绘制高亮散点(红色)
plt.scatter(filtered_df['PTS'], filtered_df['BLK'], color='#ff4444', s=100, label='1.5<BLK<3')

# 4. 批量标注球员名称
for idx, row in filtered_df.iterrows():
    # 调整xytext参数可以让标签偏移,避免遮挡散点
    plt.annotate(row['Player'], 
                xy=(row['PTS'], row['BLK']),
                xytext=(5, 5),  # 标签相对于点的偏移量
                textcoords='offset points')

plt.xlabel('得分(PTS)')
plt.ylabel('盖帽(BLK)')
plt.title('球员得分vs盖帽(高亮盖帽1.5-3的球员)')
plt.legend()
plt.show()

常见问题排查

  • 布尔索引要用&而不是and,并且每个条件要加括号,不然会报错
  • 如果标注的文字挡住散点,调整xytext的数值,比如改成(-5, -5)可以让标签在点的左下方
  • 确保你的DataFrame列名和代码里的一致(比如BLK、Player),别打错字

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 03:42:11