geom_density:为不同的 x 轴值着色密度表面

时间:2021-05-08 16:32:32

标签: r ggplot2 plot tidyverse figure

我应该如何更改代码以获得所需的结果:相当于“0”和“>25”的密度表面被着色为红色。

#simulate zero-inflated data
pi <- 0.3
mu_log <- 2
sigma_log <- 0.8
N <- 1000
y <- (1 - rbinom(N, 1, prob = pi)) * rlnorm(N, mu_log, sigma_log)

#plot
ggplot()+
  geom_density(aes(y), inherit.aes = FALSE, show.legend = FALSE, size = 1, fill="grey60", color = NA, outline.type = "upper")

从当前代码绘制

enter image description here

想要的结果应该是这样的

enter image description here

1 个答案:

答案 0 :(得分:1)

这里有一些我可以想出的想法:

#simulate zero-inflated data
pi <- 0.3
mu_log <- 2
sigma_log <- 0.8
N <- 1000
y <- (1 - rbinom(N, 1, prob = pi)) * rlnorm(N, mu_log, sigma_log)

df = data.frame(y) 
gg = ggplot(df, aes(y)) +
        geom_density(fill = "grey")
dat = ggplot_build(gg)$data[[1]]
gg + geom_area(data = subset(dat, x > 25), aes(x = x, y = y), fill = "red") +
        geom_vline(xintercept = 0, col = "red", size = 2)

enter image description here