Using ggplot to Create a Line Graph with Multiple Lines and Error Bars

The following steps will walk you through how to create a line graph with multiple lines, based on a data table of means and standard deviations.

Note: We will be using R Studio and ggplot to create our graph.

Step 1: Select and organize your data.

The table below is an example of this type of data, which you may want to display in graph format.

Original Data Table

from Hoff, E. (2003). The specificity of environmental influence: socioeconomic status affects early vocabulary development via maternal speech. Child Development, 74(5),1368-1378.

First, be sure to organize your data file appropriately. In this example, we have only means and standard deviations, rather than the full data set. Create your file in a spreadsheet program, e.g. Excel, and save it as a .csv file.

Spreadsheet of Data

Step 2: Load appropriate libraries in R Studio.

Once you open R Studio, be sure to load all appropriate libraries before you begin. We will need ggplot.

library(ggplot2)

Step 3: Import your data file.

Next, import your data file into R Studio. Be sure to use a meaningful name. You can either point and click:

Point and Click Import

or you can use code to import your data file. For example:

WordTypes <- read.csv("WordTypes.csv")

When importing your data, make sure your data show up appropriately within the Data Frame window. If not, adjust the settings on the left side of this window, e.g. Heading, Separator, Decimal, etc.

Data Import Window

Step 4: Create a variable to define your error bars.

You will need to create a variable to define your error bars. We will call this limits. You can see this is based on our Y value, called WordTypes, and adding and subtracting our standard deviation values, called Bar.

Our example code is:

limits <- aes(ymax = WordTypes + Bar, ymin = WordTypes - Bar)

Step 5: Create your plot.

The ggplot funtion allows you to specify what data you would like to display. By using the “+” you can then add features to your graph. In this case, in the geom_line function, you must specify your group in order to create 2 separate lines on the line graph. You can also see that the error bars are defined by your previously created variable, limits.

The following is our example code:

ggplot(WordTypes, aes(x = Time, y = WordTypes, colour = SES)) + geom_line(aes(group = SES)) + 
    geom_point() + geom_errorbar(limits, width = 0.25)

plot of chunk unnamed-chunk-4

Step 6: Export and label your graph.

Export your graph by selecting export, and then save the plot as an image. See below.

Exporting Image

Open your graph in photo editing software, e.g. paint, or word processing software, e.g. Word, to add titles and extra labels.

Graph with Labels

Helpful hints and resources:

  1. Organizing your data file:
  2. Writing your R code: