如何自动定义从 ggplot2 上的 stat_function 开始的水平线的高度?

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

我正在尝试使用 geom_segment 在该密度图上方添加一条水平线,但是此函数的参数请求 yyend。由于 - 根据 SD - 曲线的高度可能会有所不同,我想知道如何获得 stat_function 最大高度并将其用作添加线的参考。

Density plot to add a line above the normal curve

基础代码:

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

我添加了这行:

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

结果是: