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

如何在散点图中仅为Outside为True的点标注DataFrame索引值?

解决方案:仅标注指定条件的散点

当然可以轻松实现这个需求!你只需要在现有绘图代码的基础上,添加一段逻辑来筛选Outside列为True的行,然后给这些点单独添加标注即可。下面是修改后的完整代码:

import seaborn as sns
import matplotlib.pyplot as plt

# Initialize Figure and Axes object
fig, ax = plt.subplots(figsize=(15,8))
# Load in the data
data = sqlDf2
y = data['Success'].values
x = data['Total'].values
up95 = (data['Upper95'].values)*100
low95 = (data['Lower95'].values)*100
up99 = (data['Upper99'].values)*100
low99 = (data['Lower99'].values)*100
middleLine = (data['Pred'].values)*100
holdOrg = sqlDf2.index.tolist()

# Create plot
sns.regplot(x="Total", y="Success", data=data, fit_reg=False, ax=ax)
plt.plot(x, up95, linewidth=2)
plt.plot(x, low95, linewidth=2)
plt.plot(x, up99, linewidth=2)
plt.plot(x, low99, linewidth=2)
plt.ylim(0, 100)
plt.margins(x=0)

# 新增:仅标注Outside为True的点,内容为Org索引
for org_idx, row in data[data['Outside'] == True].iterrows():
    # 用plt.text添加标注,x是Total值,y是Success值,标注内容为Org索引
    # 这里加了一点偏移(x+5, y+1)避免标注挡住散点,你可以根据需求调整
    plt.text(row['Total'] + 5, row['Success'] + 1, org_idx, 
             ha='center', va='bottom', fontsize=10)

# Show plot
plt.show()

关键逻辑说明:

  • 筛选目标行:用data[data['Outside'] == True]快速筛选出需要标注的行,这是pandas中常用的布尔索引方式。
  • 遍历添加标注:通过iterrows()遍历筛选后的行,它会返回每一行的索引(也就是你需要的Org值)和行数据。
  • 调整标注位置:plt.text()的前两个参数是标注的坐标,我这里给Total加了5,Success加了1,让标注稍微偏离散点,避免遮挡;ha='center'和va='bottom'用来控制标注的对齐方式,让它看起来更整齐。

如果你的散点分布比较密集,还可以调整fontsize或者偏移量,让标注更清晰哦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:32:35