将ID添加到R中ggplot barplot中的异常值

adding ID to outliers in ggplot barplot in R

我创建了一个堆叠条形图

ggplot(data %>% count(x, y),
        aes(x, n, fill = factor(y))) + 
geom_bar(stat="identity")+
theme_light()+
theme(plot.title = element_text(hjust=0.5))

在 50,54 和 60 处有(可能的)异常值。如何将他们的 ID 添加到图表中?

也许 geom_text(data=mydata%>%filter(just.the.outliers) ? 另见:RE: Alignment of numbers on the individual bars with ggplot2

如果您 post 您的数据,我将使用它修改此答案。但基本上你想要

df %>%
    count(x, y) %>%
    ggplot(aes(x = x, y = n, fill = y)) +
    geom_col() +
    geom_text(aes(label = x), data = . %>% filter(x >= thresh), vjust = 0, nudge_y = 0.1)

其中 thresh 是您设置的某个阈值——可能是一个有意义的任意截止点,或者可能是与 x 平均值的 3 个标准差,或其他。您可以将它存储在一个外部变量中,您可以在您的数据框中创建一个布尔列,或者您可以在您的 geom_text 中内联计算它——完全取决于您。 vjust = 0, nudge_y = 0.1 将标签放在与异常值相对应的条形上方。