Based on ggplot2, I am wondering how I can visualize an interquartile range for each group (Type), where the densities of each group are in one big figure as shown below:
In this current figure, dots represent x values corresponding to the maximum value of y, where the minimum/maximum values of grey line represent 2.5% and 97.5% quantiles of each group.
Here in each plot, I have three dots, which are the maximums in three groups.
HOWEVER, What I need is to have just one dot (one x value) for each group, and I am lost from here.
Please help me!
Just in case, I attached the code that can reproduce the figure.
my_data <- data.frame(mean = c(0.04, 0.015, -0.04),
stdev = c(0.019, 0.019, 0.02),
Type = factor(c("A",
"B",
"C")))
# points at which to evaluate the Gaussian densities
x <- seq(-0.1, 0.1, by = 0.001)
# build list of Gaussian density vectors based on means and standard deviations
pdfs <- mapply(dnorm, mean = my_data$mean, sd = my_data$stdev, MoreArgs = list(x = x),
SIMPLIFY = FALSE)
# add group names
names(pdfs) <- my_data$Type
# convert list to dataframe
pdfs <- do.call(cbind.data.frame, pdfs)
# Summary stat
x.com <- data.frame(pdfs, x)
sum_stat <- matrix(NA, ncol = 7, nrow = 3)
for (i in 1:3){
sum_stat[i,1] <- min(x.com[,4][x.com[,i]==quantile(x.com[,i], probs=.025)])
sum_stat[i,2] <- quantile(x.com[,i], probs=.025)
sum_stat[i,3] <- x.com[,4][x.com[,i]==max(x.com[,i])]
sum_stat[i,4] <- max(x.com[,i])
sum_stat[i,5] <- max(x.com[,4][x.com[,i]==quantile(x.com[,i], probs=.975)])
sum_stat[i,6] <- quantile(x.com[,i], probs=.975)
}
sum_stat <- data.frame(sum_stat)
sum_stat[,7] <- colnames(x.com)[1:3]
sum_stat[,7] <- as.factor(sum_stat[,7])
colnames(sum_stat) <- c("left", "left_val", "max", "max_val", "right", "right_val", "variable")
sum_stat
# convert dataframe to tall format
# library(tidyr)
pdfs$x <- x
tall_df <- gather(pdfs, Type, density, -x)
tall_df$Type
tt <- transform(tall_df,
Type=factor(Type,levels=c("A",
"B",
"C")))
ggplot(tt, aes(x = x, y = density, fill = Type, color = Type)) +
geom_line() +
geom_point(inherit.aes = FALSE,
data = sum_stat,
aes(x = max, y = 0, alpha=0.4),
show.legend = FALSE) +
geom_errorbarh(inherit.aes = FALSE,
data = sum_stat,
aes(xmin = left, xmax = right, y = 0, alpha=0.4),
height = 0.1, show.legend = FALSE) +
facet_wrap(~ Type, ncol = 1) +
theme(strip.background = element_blank(),
strip.text.x = element_blank())

