Error bars are a basic chart type in ggplot and easy to execute.
Data
Synthetic sensor data set is created.
1 2 3 4 5 6 7 8 9 10 11 |
library(ggplot2) # Create synthetic sensor data set.seed(1) n <- 4 synth <- data.frame(location = rep(c("1", "2"), each = 2), sensor = rep(c("A", "B"),2), mean = rnorm(n, 6.5, 2), sd = abs(rnorm(n, 0.5, 0.25))) synth <- transform(synth, ci = synth$sd * 2.62) |
View the data:
1 2 3 4 5 6 |
print(synth) location sensor mean sd ci 1 1 A 7.739 0.380 0.996 2 1 B 6.387 0.604 1.583 3 2 A 6.188 0.839 2.199 4 2 B 3.558 0.474 1.242 |
Basic Error Bar Syntax
1 2 3 4 5 |
# Plot Skeleton p <- ggplot(synth, aes(x = location, y = mean, fill = sensor, group = sensor)) # Plot1: Error bars p + geom_errorbar(aes(ymin = mean - sd, ymax = mean + sd), width = 0.1) |
Error Bar Aesthetics
geom_errorbar() takes the following aesthetic arguments: x axis data, ymin and ymax value data, color, linetype, horizontal bar width, and the alpha or transparency level. Error bars can be plotted alone or in layers with points, line and bars, as shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# Plot2: Point plot with error bars p + geom_point(size=3, shape=21) + geom_errorbar(aes(ymin = mean-sd, ymax = mean+sd), width=0.1) # Plot3: Line chart of sensor means with error bars p + geom_point(size=3, shape=21) + geom_line(aes(color=sensor)) + geom_errorbar(aes(ymin = mean-sd, ymax = mean+sd, color=sensor), width=0.1) # Plot4: Bar chart of sensor means with error bars p + geom_bar(position=position_dodge(), stat="identity") + geom_errorbar(aes(ymin = mean-sd, ymax = mean+sd), color="black", width=0.1, position=position_dodge(0.9)) # Plot5: Bar chart of sensor means with 95% CI p + geom_bar(position=position_dodge(), stat="identity") + geom_errorbar(aes(ymin = mean-ci, ymax = mean+ci), color="black", width=0.1, position=position_dodge(0.9)) |