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

标签 r ggplot2 plot density-plot

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

Density plot with a vertical line (not aligned)

enter image description here

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

最佳答案

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

关于r - 如何在单个 ggplot2 中对齐图层(密度图和垂直线),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60081940/

相关文章:

r - 对 n 个值进行排序的所有可能方式

string - 用 Latex 代码替换字符串向量中的重音符号

r - ggplot2 安装未找到新的 Rcpp,Ubuntu 14.04

r - ggplot 和轴编号和标签

r - 更改厚度中线 geom_boxplot()

python - 在 Sympy.mpmath.plot 中更改图形大小

R ggplot2 - 在一个方面对每对执行成对测试并使用 ggsignif 显示 p 值

r - 朴素贝叶斯的特征选择

python - 在 IDE (PyCharm) 中使用时,Matplotlib 不会更新绘图

r - 为 GoogleMap 绘图添加透明度(loa 包)