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

问题描述 投票:3回答:1

我知道有一种方法可以使用箱形图绘制密度图,如下所示:因此,基本上,在该图中,使用了中位数和四分位数。

enter image description here

但是,我不知道如何表达每个密度图的均值和置信区间。我想知道是否有一种方法可以基于ggplot2在x轴上绘制“平均和置信区间”线(而不是具有中位数和四分位数的箱形图)。

我尝试使用geom_errorbarh,但未能生成我想看到的内容。

这里是保存在sum_stat中的具有均值和95%置信区间计算的R代码。

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)

我希望听到大家的声音!

谢谢。

r ggplot2 plot confidence-interval
1个回答
0
投票

要使用geom_errorbarh,必须通过inherit.aes = FALSE才能绘制均值和CI。 (注意:我也将您的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)

enter image description here

这是您要寻找的吗?

© www.soinside.com 2019 - 2024. All rights reserved.