rggplot2density-plothorizontal-line

How to automatically define the height of a horizontal line from a stat_function on ggplot2?


I am trying to add a horizontal line above this density plot using the geom_segment, however the arguments of this function request y and yend. Since - depending on the SD - the height of the curve can vary, I would like to know how to obtain the stat_function maximum height and use it as a reference to add the line.

Density plot to add a line above the normal curve

enter image description here

The base code:

all_mean <- mean(mtcars$wt,na.rm = T)%>% round(2)
all_sd <- sd(mtcars$wt,na.rm = T)%>% round(2)
my_score <- mtcars[1,"wt"]


dd <- function(x) { dnorm(x, mean=all_mean, sd=all_sd) }

z <- (my_score - all_mean)/all_sd

pc <- round(100*(pnorm(z)), digits=0)

t1 <- paste0(as.character(pc),"th percentile")

p33 <- all_mean + (qnorm(0.3333) * all_sd)
p67 <- all_mean + (qnorm(0.6667) * all_sd)

funcShaded <- function(x, lower_bound) {
  y = dnorm(x, mean = all_mean, sd = all_sd)
  y[x < lower_bound] <- NA
  return(y)
}

greenShaded <- function(x, lower_bound) {
  y = dnorm(x, mean = all_mean, sd = all_sd)
  y[x > (all_mean*2)] <- NA
  return(y)
}

ggplot(data.frame(x=c(min(mtcars$wt-2), max(mtcars$wt+2))), aes(x=x)) +
  stat_function(fun=dd, colour="black") +
  stat_function(fun = greenShaded, args = list(lower_bound = pc), 
                geom = "area", fill = "green", alpha = 1)+
    stat_function(fun = funcShaded, args = list(lower_bound = my_score), 
                geom = "area", fill = "white", alpha = .9)+
  geom_vline(aes(xintercept=my_score), colour="black")

Solution

  • I added the line:

    geom_segment(aes(x=0, y=max(dd(x)*1.05), xend=6, yend=max(dd(x))*1.05), colour="firebrick3")
    

    And result is:

    enter image description here