ggplot 中的自动异常值标记

Automatic outlier labeling in ggplot

我在循环中使用 ggplot 为我的 200 个变量中的每一个生成散点图 - V1、V2 等。为了使散点图更清晰,我希望能够自动标记异常值。我想为每个唯一变量标记大于第 95 个百分位数值的点。

我尝试使用此处的代码-Label points in geom_point,但是,这更像是一种手动标记异常值的方法。我有大约 200 个变量,无法为每个变量指定值。

同样,我能找到的最接近的解决方案来自上面的 link: county_list[i] 是我正在循环的变量列表

    ggplot(nba, aes(x= county_list[i], y= Afd_2017, colour="green", label=Name))+
    geom_point() +
    geom_text(aes(label=ifelse(value_of_V[i]>24,as.character(Name),'')),hjust=0,vjust=0)

我想要的是这样的:

    ggplot(nba, aes(x= county_list[i], y= Afd_2017, colour="green", label=Name))+
    geom_point() +
    geom_text(aes(label=ifelse((value_of_V[i] >greater-than- 
    value-of-the-95-Percentile-of-the- 
    value_of_V[i]),as.character(Name),'')),hjust=0,vjust=0)

您可以使用 lapply/map

创建地块列表
library(ggplot2)

list_plots <- lapply(nba[-1], function(data) 
     ggplot(nba, aes(x= MIN, y = data, colour="green", label=Name))+
     geom_point() +
     geom_text(aes(label= ifelse(data > quantile(data, 0.95),
     as.character(Name),'')),hjust=0,vjust=0))

然后您可以通过使用 [[

对列表进行子集化来访问各个地块
list_plots[[6]]

list_plots[[7]]

我们可以使用 walk 来自 purrr

library(purrr)
library(ggplot2)    

list_plots <- walk(nba[-1], ~ 
   ggplot(nba, aes(x= MIN, y = .x, colour="green", label=Name))+
       geom_point() +
       geom_text(aes(label= ifelse(data > quantile(data, 0.95),
       as.character(Name),'')),hjust=0,vjust=0))

并使用 pluck

获取 list 个元素
pluck(list_plots, 4)