簡體   English   中英

ggplot2:具有均值/95% 置信區間線的密度圖

[英]ggplot2: Density plot with mean / 95% confidence interval line

我知道有一種方法可以用箱線圖繪制密度圖,如下所示: 所以基本上,在這個圖中,使用了中位數和四分位數。

在此處輸入圖片說明

但是,我無法找出如何表達每個密度圖的均值和置信區間 我想知道是否有一種方法可以基於 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)

我期待聽到你們所有人的任何消息!

謝謝你。

要使用geom_errorbarh ,您必須通過inherit.aes = FALSE才能繪制均值和 CI。 (注意:我還在數據sum_stat轉換您的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)

在此處輸入圖片說明

這是您要找的嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM