QCBS R Workshops

This series of 10 workshops walks participants through the steps required to use R for a wide array of statistical analyses relevant to research in biology and ecology. These open-access workshops were created by members of the QCBS both for members of the QCBS and the larger community.

The content of this workshop has been peer-reviewed by several QCBS members. If you would like to suggest modifications, please contact the current series coordinators, listed on the main wiki page

Workshop 3: Intro to ggplot2

Developed by: Xavier Giroux-Bougard, Maxwell Farrell, Amanda Winegardner, Étienne Low-Decarie and Monica Granados

Summary: In this workshop we will build on the data manipulation and visualization skills you have learned in base R by introducing ggplot2, an excellent plotting alternative to base R that can be used for both diagnostic and publication quality plots. We will then introduce tidyr and dplyr, two powerful tools to manage and re-format your dataset, as well as apply simple or complex functions on subsets of your data. This workshop will be useful for those progressing through the entire workshop series, but also for those who already have some experience in R and would like to become proficient with new tools and packages.

Link to new Rmarkdown presentation

Link to old Prezi presentation

Download the R script for this lesson.

Whether you are calculating summary statistics (e.g. Excel), performing more advanced statistical analysis (e.g. JMP, SAS, SPSS), or producing figures and tables (e.g. Sigmaplot, Excel), it is easy to get lost in your workflow when you use a variety of software. This becomes especially problematic every time you import and export your dataset to accomplish a downstream task. With each of these operations, you increase your risk of introducing errors into your data or losing track of the correct version of your data. The R statistical language provides a solution to this by unifying all of the tools you need for advanced data manipulation, statistical analysis, and powerful graphical engines under the same roof. By unifying your workflow from data to tables to figures, you reduce your chances of making mistakes and make your workflow easily understandable and reproducible. Believe us, the future “you” will not regret it! Nor will your collaborators!

The most flexible and complete package available for advanced data visualization in R is ggplot2. This packages was created for R by Hadley Wickham based on the Grammar of Graphics by Leland Wilkinson. The source code is hosted on github: https://github.com/hadley/ggplot2. Today we will walk you through the basics of ggplot2, and hopefully its potential will speak for itself and you will have the necessary tools to explore its use for your own projects.

To get started you will need to open RStudio and and load the necessary package from the CRAN repository:

|
install.packages("ggplot2")
library(ggplot2)

Using ''qplot()''

Let's jump right into it then! We will build our first basic plot using the qplot() function in ggplot2. The quick plot function is built to be an intuitive bridge from the plot() function in base R. As such, the syntax is almost identical, and the qplot() function understands how to draw plots based on the types of data (e.g. factor, numerical, etc…) that are mapped. Remember you can always access the help file for a function by typing the command preceded by ?, such as:

|
?qplot

If you checked the help file we just called, you will see that the 3 first arguments are:

  • data
  • x
  • y

Load data

Before we go forward with qplot(), we need some data to assign values to these arguments. We will first play with the iris dataset, a famous dataset of flower dimensions for three species of iris collected by Edgar Anderson in the Gaspé peninsula right here in Québec! It is already stored as a data.frame directly in R. To load it and explore its structure and the different variables, use the following commands:

|
?iris
data(iris)
head(iris)
str(iris)
names(iris)

Basic scatter plot

Let's build our first scatter plot by mapping the x and y variables from the iris dataset in the qplot() function as follows:

|
qplot(data = iris, x = Sepal.Length, y = Sepal.Width)

Basic scatter plot (categorical variables)

As mentioned previously, the qplot() function understands how to draw a plot based on the mapped variables. In the previous example we used two numerical variables and obtained a scatter plot. However, qplot() will also understand categorical variables:

|
qplot(data = iris, x = Species, y = Sepal.Width)

Adding axis labels and titles

If you return to the qplot() function's help file, there are several more arguments that can be used to modify different aspects of your figure. Lets start with adding labels and titles using the xlab, ylab and main arguments:

|
qplot(data = iris,
      x = Sepal.Length,
      xlab = "Sepal Length (mm)",
      y = Sepal.Width,
      ylab = "Sepal Width (mm)",
      main = "Sepal dimensions")

Using the qplot() function, build a basic scatter plot with a title and axis labels from one of the CO2 or BOD data sets in R. You can load these and explore their contents as follows:

|
?CO2
data(CO2)

CO2 example solution


The grammar of graphics is a framework for data visualization that dissects every component of a graph into individual components. Its “awesome factor” is due to this ability, which allows you to flexibly change and modify every single element of a graph. Let's go over a few of these elements, or “layers”, together. First and foremost, a graph requires data, which can be displayed using:

  • aesthetics (aes)
  • geometric objects (geoms)
  • transformations
  • axis (coordinate system)
  • scales

Aesthetics: ''aes()''

In ggplot2, aesthetics are a group of parameters that specify what and how data is displayed. Here are a few arguments that can be used within the aes() function:

  • x: position of data along the x axis
  • y: position of data along the y axis
  • colour: colour of an element
  • group: group that an element belongs to
  • shape: shape used to display a point
  • linetype: type of line used (e.g. solid, dashed, etc…)
  • size: size of a point or line
  • alpha: transparency of an element

Geometric objects: ''geoms''

Geometric objects, or geoms, determine the visual representation of your data:

  • geom_point(): scatterplot
  • geom_line(): lines connected to points by increasing value of x
  • geom_path(): lines connected to points in sequence of appearance
  • geom_boxplot(): box and whiskers plot for categorical variables
  • geom_bar(): bar charts for categorical x axis
  • geom_histogram(): histogram, geom_bar for continuous x axis

How it works

  1. Create a simple plot object: plot.object ← ggplot() OR qplot()
  2. Add graphical layers/complexity: plot.object ← plot.object + layer()
  3. Repeat step 2 until statisfied, then print: print(plot.object)

Using these steps, we build a final product by laying individual elements over each other until we are satisfied:

credit: Vanderbilt 2007

Additional resources

Our brief intro on the grammar of graphics is not enough to cover even a small fraction of the all the layers and elements that can be used in visualization. Instead, we introduce the most commonly used, in the hopes that your travels will bring you to the following resources when you take your next steps:

  • ''ggplot2'' documentation: this is the best resource for a complete list of available elements and the list of arguments needed for each, as well as useful examples
  • SAPE: the Software And Programmer Efficiency research group devotes a full section of their website on appropriate usage of different elements in ggplot2, along with pertinent examples
  • The Grammar of Graphics: this book by Leland Wilkinson explains the data visualization framework which ggplot2 uses.
  • ggplot2: this book by Hadley Wickham, who authored ggplot2 to implement the grammar of graphics in R.

''qplot()'' vs ''ggplot()''

Often, we only require some quick and dirty plots to visualize data, making the qplot() function perfect. As stated above, if we assign a qplot to an object in R, we can still add more complex layers to our base plot like this: plot.object ← plot.object + layer(). However, the qplot() function simply wraps the raw ggplot() commands into a form similar to the plot() function in base R. Let's dissect what ggplot2 is actually doing when we use qplot().

  • qplot():
|
qplot(data = iris,
      x = Sepal.Length,
      xlab = "Sepal Length (mm)",
      y = Sepal.Width,
      ylab = "Sepal Width (mm)",
      main = "Sepal dimensions")
  • ggplot():
|
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width)) +
    geom_point() +
    xlab("Sepal Length (mm)") +
    ylab("Sepal Width (mm)") +
    ggtitle("Sepal dimensions")

In the raw ggplot() function, we first specify the data and then map the x and y variables in aes(). We subsequently add each individual element one at a time, which unleashes the full potential of grammar of graphics. As your needs shift towards more advanced features in the ggplot2 package, it is good practice to use raw syntax of the ggplot() function, as we will do in the rest of the workshop.

Assign plot to an object

Before we get started with some more advanced features, let's build a foundation by assigning the previous plot to an object:

|
basic.plot <- ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width)) +
    geom_point()+
    xlab("Sepal Length (mm)")+
    ylab("Sepal Width (mm)")+
    ggtitle("Sepal dimensions")

Let's add colours and shapes to our basic scatter plot by adding these as arguments in the aes() function:

|
basic.plot <- basic.plot + aes(colour = Species, shape = Species)
basic.plot

It's alive!LOL

We already have some geometric objects in our basic plot which we added as points using geom_point(). Now we let's add some more advanced geoms, such as linear regressions with geom_smooth():

|
linear.smooth.plot <- basic.plot + geom_smooth(method = "lm", se = FALSE)
linear.smooth.plot

You can even use emojis as your geoms!!! You need the emoGG package by David Lawrence Miller.

|
devtools::install_github("dill/emoGG")
library(emoGG)
#you have to look up the code for the emoji you want
emoji_search("bear")
830   bear 1f43b     animal
831   bear 1f43b     nature
832   bear 1f43b       wild
 
ggplot(iris, aes(Sepal.Length, Sepal.Width, color = Species)) +
  geom_emoji(emoji="1f337")


Produce a colourful plot with linear regression (or other smoother) from built in data such as the CO2 dataset or the msleep dataset:

|
?CO2
data(CO2)
?msleep
data(msleep)

CO2 example solution


Data becomes difficult to visualize when there are multiple factors accounted for in experiments. For example, the CO2 data set contains data on CO2 uptake for chilled vs non-chilled treatments in a species of grass from two different regions (Québec and Mississippi). Let's build a basic plot using this data set:

|
CO2.plot <- ggplot(data = CO2, aes(x = conc, y = uptake, colour = Treatment)) +
    geom_point() +
    xlab("CO2 Concentration (mL/L)") +
    ylab("CO2 Uptake (umol/m^2 sec)") +    
    ggtitle("CO2 uptake in grass plants")
CO2.plot

If we want to compare regions, it is useful to make two panels, where the axes are perfectly aligned for data to be compared easily with the human eye. In ggplot2, we can accomplish this with the facet_grid() function. Briefly its basic syntax is as follows: plot.object + facet_grid(rows ~ columns). Here the rows and columns are variables in the data.frame which are factors we want to compare by separating the data into panels. To compare data between regions, we can use the following code:

|
CO2.plot <- CO2.plot + facet_grid(. ~ Type)
CO2.plot

*Note: you can stack the two panels by using facet.grid(Type ~ .).

Now that we have two facets, let's observe how the CO2 uptake evolves as CO2 concentrations rise, by adding connecting lines to the points using geom_line():

|
CO2.plot + geom_line()

As we can see from the previous figure, the lines are connecting vertically across three points for each treatment. If we look into the details of the CO2 dataset, this is each treatment in each region has 3 replicates. If we want to plot lines connecting data points for each replicate separately, we can add map a group aesthetic to the “geom_line()” function as follows:

|
CO2.plot <- CO2.plot + geom_line(aes(group = Plant))
CO2.plot


Explore a new geom and other plot elements with your own data or built in data. Look here or here for some inspiration and great examples!

|
data(msleep)
data(OrchardSprays)

OrchardSprays boxplot example


There are many options available to save your beloved creations to file.

Saving plots in RStudio

In RStudio, there are many options available to you to save your figures. You can copy them to the clipboard or export them as any file type (png, jpg, emf, tiff, pdf, metafile, etc…):

Saving plots with code

In instances where you are producing many plots (e.g. during long programs that produces many plots automatically while performing analysis), it is useful to save many plots in one file as a pdf. This can be accomplished as follows:

|
pdf(“./plots/todays_plots.pdf)
print(basic.plot)
print(plot.with.linear.smooth)
print(CO2.plot)
graphics.off()

Saving plots - other options

There are many other options, of particular note is ggsave() as it will write directly to your working directory all in one line of code and you can specify the name of the file and the dimensions of the plot:

|
ggsave("CO2 plot.pdf", CO2.plot, height = 8.5, width = 11, units = "in")

The ggplot2 package automatically chooses colours for you based on the chromatic circle and the number of colours you need. However, in many instances it is useful to use your own colours. You can easily accomplish this using the scale_colour_manual() function:

|
CO2.plot + scale_colour_manual(values = c("nonchilled" = "red", "chilled" = "blue"))

For added control, you can also use all hexadecimal codes for colours specifically tailored to your needs. A great resource for hex codes is the internets. Just Google “RGB to Hex” and a colour slider will be returned. You can input the hex codes directly into the scale_colour_manual() function instead of colour names.

If you are looking for a colour palette to use across your variables and don't have specific colours in mind. The viridis function will use colour blind and printer friendly colours based on four palettes. You can specify which palette to use, how many colours to use and where to start and end on the spectrum of the palette. Let try adding the default palette “D” to our CO2 plot for the two colours we need.

|
CO2.plot + scale_colour_manual(values = viridis(2, option = "D"))

BONUS

Check out the following links/packages for some really awesome colour fun:

  • Cookbook for R: this ggplot2 and colours entry in the Cookbook for R has tons of great ideas and many color charts and ramps to suggest
  • RColorBrewer: this R package is available on the CRAN repository, and is loaded with custom colour ramps which can be integrated to ggplot2 using the scale_color_brewer() function.
  • WesAnderson: this r package is available from the github repository, and is loaded with fun and rich color ramps based on themes from your favorite Wes Anderson movies!

You can control all the aspects of the axes and scales used to display your data (eg break, labels, positions, etc…):

|
CO2.plot + scale_y_continuous(name = "CO2 uptake rate",
                              breaks = seq(5, 50, by = 10),
                              labels = seq(5, 50, by = 10), 
                              trans = "log10")

This is were we get to the “publication quality” part of the ggplot2 package. I am sure that by now, some of you have formed opinions about that grey background… You either love it or hate it (like liver and brussel sprouts). Worry no longer, you will not have to include figures with a grey background in that next publication your are submitting to Nature!

Like every other part of the grammar of graphics, we can modify the theme of the plot to suit our needs, or higher sense of style! Its as simple as:

|
plot.object + theme()

There are way too many theme elements built into the ggplot2 package to mention here, but you can find a complete list in the ggplot theme vignette. Instead of modifying the many elements contained in theme(), you can start from theme functions, which contain a specific set of elements from which to start. For example we can use the “black and white” theme like this:

|
CO2.plot + theme_bw()

Build your own theme

Another great strategy is to build a theme tailored to your own publication needs, and then apply it to all you figures:

|
mytheme <- theme_bw() + 
           theme(plot.title = element_text(colour = "red")) +
           theme(legend.position = c(0.9, 0.9))
CO2.plot + mytheme

The ggtheme package

The ggtheme package is a great project developed by Jeffrey Arnold on github and also hosted on the CRAN repository, so it can easily be installed as follows:

|
install.packages("ggthemes")
library(ggthemes)

The package contains many themes, geoms, and colour ramps for ggplot2 which are based on the works of some of the most renown and influential names in the world of data visualization, from the classics such asEdward Tufte to the modern data journalists/programmers at FiveThirtyEight blog.

Here is a quick example which uses the Tufte's boxplots and theme, as you can see he is a minimalist:

|
data(OrchardSprays)
tufte.box.plot  <- ggplot(data = OrchardSprays, aes(x = treatment, y = decrease)) +
                     geom_tufteboxplot() +
                     theme_tufte()
tufte.box.plot

While hardcore programmers might laugh at you for using a GUI, there is no shame in using them! Jeroen Schouten, who is about as hardcore a programmer as you can get, understood the learning curve for begginners could be steep and so designed an online ggplot2 GUI. While it will not be as fully functional as coding the grammar of graphics, it is very complete. You can import from excel, google spreadsheets, or any data format, and build a few plots using some tutorial videos. The great part is that it shows you the code you have generated to build your figure, which you can copy paste into R as a skeleton on which to add some meat using more advanced features such as themes.


Example with the air quality dataset on using both wide and long data formats

|
> head(airquality)
 Ozone Solar.R Wind Temp Month Day
1    41     190  7.4   67     5   1
2    36     118  8.0   72     5   2
3    12     149 12.6   74     5   3
4    18     313 11.5   62     5   4
5    NA      NA 14.3   56     5   5
6    28      NA 14.9   66     5   6

The dataset is in wide format, where measured variables (ozone, solar.r, wind and temp) are placed in their own columns.

Diagnostic plots using the wide format + ggplot2

1: Visualize each individual variable and the range it displays for each month in the timeseries

|
fMonth <- factor(airquality$Month) # Convert the Month variable to a factor. 
 
ozone.box <- ggplot(airquality, aes(x = fMonth, y = Ozone)) + geom_boxplot()
solar.box <- ggplot(airquality, aes(x = fMonth, y = Solar.R)) + geom_boxplot()
temp.box  <- ggplot(airquality, aes(x = fMonth, y = Temp)) + geom_boxplot()
wind.box  <- ggplot(airquality, aes(x = fMonth, y = Wind)) + geom_boxplot()

You can use grid.arrange() in the package gridExtra to put these plots into 1 figure.

|
combo.box <- grid.arrange(ozone.box, solar.box, temp.box, wind.box, nrow = 2) 
# nrow = number of rows you would like the plots displayed on.

This arranges the 4 separate plots into one panel for viewing. Note that the scales on the individual y-axes are not the same:

600

2. You can continue using the wide format of the airquality dataset to make individual plots of each variable showing day measurements for each month.

|
ozone.plot <- ggplot(airquality, aes(x = Day, y = Ozone)) +
    geom_point() +
    geom_smooth() +
    facet_wrap(~ Month, nrow = 2)
 
solar.plot <- ggplot(airquality, aes(x = Day, y = Solar.R)) +
    geom_point() +
    geom_smooth() +
    facet_wrap(~ Month, nrow = 2)
 
wind.plot <- ggplot(airquality, aes(x = Day, y = Wind)) +
    geom_point() +
    geom_smooth() +
    facet_wrap(~ Month, nrow = 2)
 
temp.plot <- ggplot(airquality, aes(x = Day, y = Temp)) +
    geom_point() +
    geom_smooth() +
    facet_wrap(~ Month, nrow = 2)

You could even then combine these different faceted plots together(though it looks pretty ugly at the moment):

|
combo.facets <- grid.arrange(ozone.plot, solar.plot, wind.plot, temp.plot, nrow = 4)

BUT, what if I'd like to use facet_wrap() for the variables as opposed to by month or put all variables on oneplot?

Change data from wide to long format (See back to Section 2.3)

|
air.long <- gather(airquality, variable, value, -Month, -Day)
air.wide <- spread(air.long , variable, value)

Use air.long:

|
fMonth.long <- factor(air.long$Month)
weather <- ggplot(air.long, aes(x = fMonth.long, y = value)) +
    geom_boxplot() +
    facet_wrap(~ variable, nrow = 2)

Compare the weather plot with combo.box

600

This is the same data but working with it in wide versus long format has allowed us to make different looking plots.

The weather plot uses facet_wrap to put all the individual variables on the same scale. This may be useful in many circumstances. However, using the facet_wrap means that we don't see all the variation present in the wind variable.

In that case, you can modify the code to allow the scales to be determined per facet by setting scales=“free”

|
weather <- weather + facet_wrap(~ variable, nrow = 2, scales = "free")
weather

600

We can also use the long format data (air.long) to create a plot with all the variables included on a single plot:

|
weather2 <- ggplot(air.long, aes(x = Day, y = value, colour = variable)) +
               geom_point() + # this part will put all the day measurements on one plot
               facet_wrap(~ Month, nrow = 1) # add this part and again, the observations are split by month
weather2


Here are some great resources for learning ggplot2 that we used when compiling this workshop:

ggplot2

Lecture notes from Hadley's course Stat 405 (the other lessons are awesome too!)

BONUS! Check out R style guides to help format your scripts for easy reading: