在ggplot stat_密度()中阴影尾部

问题描述 投票:0回答:1

我已经在 ggplot 中生成了一个密度图,现在想对第 95 个百分位数以北的分布尾部进行阴影处理。这实现了我想要的:

library(dplyr)
library(ggplot2)

mtcars |> 
  ggplot(aes(disp)) + 
  geom_density() +
  geom_density(aes(x = disp, 
                   y = if_else(x > quantile(mtcars$disp, 0.95), 
               after_stat(density), NA)), 
               fill = "grey", alpha = 0.5)

但是,它确实需要我再次引用原始数据。有没有办法将

mtcars$disp
中的
aes()
替换为对传递给
ggplot()
的数据的引用?

r ggplot2
1个回答
0
投票
library(dplyr)
library(ggplot2)

mtcars %>% { 
  ggplot(., aes(disp)) + 
  geom_density() +
  geom_density(aes(x = disp, 
                   y = if_else(x > quantile(.$disp, 0.95), 
                               after_stat(density), NA)), 
               fill = "grey", alpha = 0.5) }

创建于 2024-04-12,使用 reprex v2.0.2

© www.soinside.com 2019 - 2024. All rights reserved.