如何在单个ggplot2中对齐图层(密度图和垂直线)

4
我正在尝试调整同时使用stat_functiongeom_vline的绘图层。我的问题是垂直线与绿色区域不完全对齐:

带有垂直线的密度图(未对齐)

enter image description here

这篇文章中,我看到了一个关于将两张独立的图表对齐的解决方案,但是在我的情况下,我想要将它们对齐在同一张图表中。
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")
1个回答

8

stat_function 会在你的区间上选择 n 个点,默认为101个。这意味着你的曲线只有有限的分辨率。只需增加 funcShaded 层的 n 值即可。

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, n = 1e3)+
  geom_vline(aes(xintercept=my_score), colour="black")

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接