Search code examples
rggplot2plottidyversefigure

geom_density: coloring density surface for different x-axis values


How should I change the code to get the desired outcome: density surface equivalent to "0" and ">25" are coloured as red.

#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")

Plot from current code

enter image description here

Desired outcome should be something like this

enter image description here


Solution

  • Here is some idea that I could come up with:

    #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