Interval Plot


This post describes how to build an interval plot with R, using ggplot2 or plotrix. An interval plot is used to compare groups similar to a box plot or a dot plot. It is used when the data is continuous. Instead of plotting the individual data point, an interval plot shows the confidence interval for the mean of the data.

Data


Firstly, we create an exemple data.

# Create example data
set.seed(923874)                
data <- data.frame(x = rep(1:10, each=2),
                   y = round(runif(20, 10, 20),2),
                   lower = round(runif(20, 0, 10),2),
                   upper = round(runif(20, 20, 30),2),
                   group = rep(c('A', 'B'), 10))

Interval plot using ggplot2 package


Here, we will be using the geom_point() function to plot the points on the ggplot and then will be using the geom_errorbar() function with it to get the confidence intervals to the plot. We created a dotplot with confidence intervals with the below code.

library(ggplot2)

ggplot(data[data$group=='A',], aes(x, y)) +        
  geom_point() +
  geom_errorbar(aes(ymin = lower, ymax = upper)) +
  theme_bw()

We add a parameter so see dotplot for group A and B simultaneously.

ggplot(data, aes(x, y, col=group)) +
  geom_point() +
  geom_line() +
  geom_errorbar(aes(ymin = lower, ymax = upper, col=group)) +
  scale_color_manual(values = c("#0073C299","#8F770099")) +
  theme_bw()

Basic interval plot using plotrix package


This example explains how to use the plotrix package to draw a confidence interval plot.

library(plotrix)

plotCI(x = data$x[data$group=='A'],              
       y = data$y[data$group=='A'],
       li = data$lower[data$group=='A'],
       ui = data$upper[data$group=='A'])




Contact

This document is a work of the statistics team in the Biostatistics and Medical Information Department at Saint-Louis Hospital in Paris (SBIM).
Based on The R Graph Gallery by Yan Holtz.

SBIM