简体   繁体   中英

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

I know that there is a way to draw a density plot with the box plot as follows: So basically, in this plot, median & quartiles were used.

在此处输入图片说明

However, I was not able to find out how I can express the mean & confidence intervals of each density plot. I am wonder if there is a way that I can plot a "mean & confidence interval" line on x-axis (instead of the box plot with median & quartiles) based on ggplot2.

I tried to use geom_errorbarh, but failed to generate what I wanted to see.

Here is the R code with mean and 95% confidence interval calculation saved in sum_stat .

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)

I look forward to hearing anything from you all!

Thank you.

To use geom_errorbarh , you will have to pass inherit.aes = FALSE in order to be able to plot mean and CI. (NB: I also transform your sum_stat in a dataframe and add a column variable to make the plot easier)

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)

在此处输入图片说明

Is it what you are looking for ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM