rggplot2areacurveshading

Shading only part of the top area under a normal curve


I'm trying to shade in an area under a normal curve, say between one standard deviation BUT not all the way to the x-axis. I need it cut off to have only the top part under the curve shaded. In my code below I'd like to shade the area under the normal curve but only between the 2 dashed lines. Can anyone help? I have seen many examples where the shading of a partial area goes all the way down to the x-axis. However, I need some way to block a user-defined lower portion of the area under the curve from being shaded.

library(ggplot2)

#generate a normal distribution plot
Fig1 <- ggplot(data.frame(x = c(-4, 4)), aes(x = x)) +
        stat_function(fun = dnorm, args = list(mean=0, sd=1.25),colour = "darkblue", size = 1.25) +
        theme_classic() +
        geom_hline(yintercept = 0.32, linetype = "longdash") +
        geom_hline(yintercept = 0.175, linetype = "longdash")
Fig1

Solution

  • You can use geom_polygon with a subset of your distribution data / lower limit line.

    library(ggplot2)
    library(dplyr)
    
    # make data.frame for distribution
    yourDistribution <- data.frame(
      x = seq(-4,4, by = 0.01),
      y = dnorm(seq(-4,4, by = 0.01), 0, 1.25)
    )
    # make subset with data from yourDistribution and lower limit
    upper <- yourDistribution %>% filter(y >= 0.175)
    
    ggplot(yourDistribution, aes(x,y)) +
      geom_line() +
      geom_polygon(data = upper, aes(x=x, y=y), fill="red") +
      theme_classic() +
      geom_hline(yintercept = 0.32, linetype = "longdash") +
      geom_hline(yintercept = 0.175, linetype = "longdash")