ggplot2:带有均值/ 95%置信区间线的密度图

4
我知道有一种方法可以绘制一个带有箱线图的密度图,如下所示:因此,在这个图中,使用了中位数和四分位数。

enter image description here

然而,我无法找到如何表达每个密度图的平均值和置信区间。我想知道是否有一种方法可以基于ggplot2在x轴上绘制“平均值和置信区间线”(而不是具有中位数和四分位数的箱线图)。
我尝试使用geom_errorbarh,但未能生成我想要看到的内容。
这是R代码,其中包含保存在sum_stat中的平均值和95%置信区间计算结果。
library(ggplot2)
library(ggridges)
library(grid)
library(reshape2)
library(ggstance)
library(dplyr)

# Generating the dataset
x <- data.frame(v1=rnorm(5000, mean = -0.02, sd = 0.022),
                v2=rnorm(5000, mean =  0.02, sd = 0.022),
                v3=rnorm(5000, mean =  0.04, sd = 0.022))

colnames(x) <- c("A", "B", "C")

# Summary statistics
mean_vec <- colMeans(x)
sd_vec   <- apply(x, 2, sd)
n        <- nrow(x)

error <- qnorm(0.975)*sd_vec/sqrt(n)
left  <- mean_vec - error
right <- mean_vec + error

sum_stat <- cbind(left, mean_vec, right)

# Melting the data
data <- melt(x)
# head(data); str(data)


ggplot(data, aes(x = value, y = variable)) +
  geom_density_ridges(aes(fill = variable), alpha=0.2, scale=0.8) +
  geom_boxploth(aes(fill = variable), width = 0.06, outlier.shape = NA)

我期待着收到大家的任何消息!谢谢。
1个回答

4

为了使用geom_errorbarh,您需要传递inherit.aes = FALSE才能绘制平均值和置信区间。(注意:我还将您的sum_stat转换为数据框,并添加了一个名为variable的列,以使绘图更加简单)

sum_stat <- data.frame(sum_stat)
sum_stat$variable = rownames(sum_stat)

ggplot(data, aes(x = value, y = variable)) +
  geom_density_ridges(aes(fill = variable), alpha=0.2, scale=0.8) +
  geom_point(inherit.aes = FALSE, data = sum_stat, 
             aes(x= mean_vec, y = variable, color = variable),show.legend = FALSE)+
  geom_errorbarh(inherit.aes = FALSE, data = sum_stat, 
                 aes(xmin = left, xmax = right, y = variable, color = variable), 
                 height = 0.1, show.legend = FALSE)

这是您正在寻找的内容吗?

输入图像描述


我修改了你的代码,最终得到了我想要看到的结果!我真诚地感谢你,dc37!! - KLee

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