Last active
January 4, 2022 03:05
-
-
Save tomhopper/9674890 to your computer and use it in GitHub Desktop.
An ordered dot plot with error bars. Demonstrates creating summarized data (e.g. means), ordering by second variable, error bars on dot plots. Based on the bar chart example at http://martinsbioblogg.wordpress.com/2014/03/19/using-r-barplot-with-ggplot2/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#' Example Cleveland-style dot plot. | |
#' Two variables plotted on an facet plot. | |
#' Ordering of the data in the first facet. | |
#' Error bars plotted with each dot. | |
library(ggplot2) | |
library(reshape2) | |
library(plyr) | |
#' Create some data for the demonstration | |
n <- 10 | |
group <- rep(1:4, n) | |
mass.means <- c(10, 20, 15, 30) | |
mass.sigma <- 4 | |
score.means <- c(5, 5, 7, 4) | |
score.sigma <- 3 | |
mass <- as.vector(model.matrix(~0+factor(group)) %*% mass.means) + | |
rnorm(n*4, 0, mass.sigma) | |
score <- as.vector(model.matrix(~0+factor(group)) %*% score.means) + | |
rnorm(n*4, 0, score.sigma) | |
data <- data.frame(id = 1:(n*4), group, mass, score) | |
#' Reorder the data on "group," sorted by "mass" | |
data <- transform(data, group = reorder(group, mass)) | |
#' Change from wide to tall format for ggplot2 | |
melted <- melt(data, id.vars=c("id", "group")) | |
#' Calculate means and standard deviations | |
means <- ddply(melted, c("group", "variable"), summarise, | |
mean=mean(value)) | |
means.sem <- ddply(melted, c("group", "variable"), summarise, | |
mean=mean(value), sem=sd(value)/sqrt(length(value))) | |
#' Create the data frame that we will use for the error bars. | |
means.sem <- transform(means.sem, lower=mean-sem, upper=mean+sem) | |
#' Note that the order of geoms matters: plot geom_errorbarh first so that the points | |
#' overlay the error bars. Reversing these plots the error bars over the dots, resulting | |
#' in a visible gray line through each dot. | |
#' Note that each geom can work with a different data set than the default passed to | |
#' ggplot(). | |
means.barplot <- ggplot(data = means, aes(x = mean, y = group)) + | |
geom_errorbarh(data=means.sem, aes(xmax=upper, xmin=lower), height = 0.15, colour = "grey50") + | |
geom_point(size = 5) + | |
facet_grid(facets= . ~ variable, scales="free_x") + | |
theme(text = element_text(size = 18)) | |
#' Plot to standard graphics window. | |
means.barplot |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment