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

Posted

技术标签:

【中文标题】如何在单个ggplot2中对齐图层(密度图和垂直线)【英文标题】:How to align layers (density plot and vertical line) in a single ggplot2 【发布时间】:2020-05-21 17:31:42 【问题描述】:

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

Density plot with a vertical line (not aligned)

在this 帖子中,我看到了一个对齐两个单独图的解决方案,但是,就我而言,我想在同一个图中对齐。

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】:

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

【讨论】:

以上是关于如何在单个ggplot2中对齐图层(密度图和垂直线)的主要内容,如果未能解决你的问题,请参考以下文章

用ggplot2绘制密度,x轴上没有线

用ggplot2画箱线图叠加图层后变成一个很奇怪的样子,求救求救?

ggplot2:如何在回归线上曲线小高斯密度?

更改ggplot2图例中单个标签的字体(变为粗体)

如何在一个 ggplot2 图中为两个几何图层添加图例?

ggplot2 密度与密度函数有何不同?