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

如何在箱线图异常值点标注观测编号以定位对应数据

没问题!给箱线图里的异常值标注对应的观测行号,确实能帮你快速定位原始数据,我给你分享两种常用工具的具体实现方法:

Python(Seaborn + Matplotlib)

  • 先说说Python的方案,用Seaborn画箱线图后,我们可以直接提取异常值的位置,再匹配对应的行号:
  • 假设你用Pandas DataFrame存储数据,看这个示例代码:
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

# 示例数据集(带异常值)
df = pd.DataFrame({
    'metric': [12, 15, 14, 16, 18, 20, 22, 25, 60, 58],
    # 如果有自定义观测编号,比如这里加个id列
    'obs_id': ['A01', 'A02', 'A03', 'A04', 'A05', 'A06', 'A07', 'A08', 'A09', 'A10']
})

# 绘制箱线图
ax = sns.boxplot(x='metric', data=df)

# 获取异常值集合(Seaborn里第二个collection是异常值点)
outlier_points = ax.collections[1].get_offsets()

# 逐个标注行号/观测ID
for point in outlier_points:
    val = point[0]
    # 找到对应的数据行,这里用自定义观测ID举例
    obs_label = df[df['metric'] == val]['obs_id'].values[0]
    # 标注文本,位置微调避免遮挡
    ax.text(point[0], point[1], obs_label, 
            fontsize=10, ha='center', va='bottom')

plt.show()

注意:如果你的数据用默认索引当行号,把obs_label改成df[df['metric'] == val].index[0]就行;如果有重复的异常值,记得循环处理所有匹配的行哦。

R(ggplot2)

  • 用R的ggplot2的话,我们可以先手动计算异常值的阈值,筛选出异常数据后再标注:
library(ggplot2)
library(dplyr)

# 示例数据集
df <- data.frame(
    metric = c(12, 15, 14, 16, 18, 20, 22, 25, 60, 58),
    obs_id = paste0("A", 1:10)  # 自定义观测编号
)

# 计算箱线图的四分位数和异常值范围
q_vals <- quantile(df$metric, c(0.25, 0.75))
iqr_val <- q_vals[2] - q_vals[1]
lower_bound <- q_vals[1] - 1.5 * iqr_val
upper_bound <- q_vals[2] + 1.5 * iqr_val

# 筛选出异常值数据
outlier_df <- df %>% filter(metric < lower_bound | metric > upper_bound)

# 画图并标注
ggplot(df, aes(x = "", y = metric)) +
    geom_boxplot(width = 0.5) +
    # 标注观测编号
    geom_text(data = outlier_df, aes(label = obs_id), 
              vjust = -0.8, size = 3.5, color = "darkred") +
    labs(title = "Boxplot with Outlier Labels") +
    theme_minimal()

两种方法都能帮你快速把异常值和原始数据行对应起来,选你常用的工具就行~

内容的提问来源于stack exchange,提问作者Máiron Chaves

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 08:10:59