This tutorial describes how to create a graph with error bars using R software and ggplot2 package. There are different types of error bars which can be created using the functions below :

• geom_errorbar()

• geom_linerange()

• geom_pointrange()

• geom_crossbar()

• geom_errorbarh()

# Add error bars to a bar and line plots

## Prepare the data

ToothGrowth data is used. It describes the effect of Vitamin C on tooth growth in Guinea pigs. Three dose levels of Vitamin C (0.5, 1, and 2 mg) with each of two delivery methods [orange juice (OJ) or ascorbic acid (VC)] are used :

• len : Tooth length

• dose : Dose in milligrams (0.5, 1, 2)

• supp : Supplement type (VC or OJ)

• In the example below, we’ll plot the mean value of Tooth length in each group. The standard deviation is used to draw the error bars on the graph.

First, the helper function below will be used to calculate the mean and the standard deviation, for the variable of interest, in each group :

Summarize the data :

## Barplot with error bars

The function geom_errorbar() can be used to produce the error bars :  Note that, you can chose to keep only the upper error bars Read more on ggplot2 bar graphs : ggplot2 bar graphs

## Line plot with error bars  You can also use the functions geom_pointrange() or geom_linerange() instead of using geom_errorbar()  Read more on ggplot2 line plots : ggplot2 line plots

# Dot plot with mean point and error bars

The functions geom_dotplot() and stat_summary() are used :

The mean +/- SD can be added as a crossbar , a error bar or a pointrange :   Read more on ggplot2 dot plots : ggplot2 dot plot

# Infos

This analysis has been performed using R software (ver. 3.1.2) and ggplot2 (ver. 1.0.0)

Contribution from ：http://www.sthda.com/english/wiki/ggplot2-error-bars-quick-start-guide-r-software-and-data-visualization 欢迎关注
0%