This lesson is still being designed and assembled (Pre-Alpha version)

Data visualization with ggplot2

Overview

Teaching: min
Exercises: min
Questions
  • How can I create publication-quality graphics using ggplot2?

Objectives
  • Produce scatter plots, boxplots, and time series plots using ggplot.

  • Set universal plot settings.

  • Describe what faceting is and apply faceting in ggplot.

  • Modify the aesthetics of an existing ggplot plot (including axis labels and color).

  • Build complex and customized plots from data in a data frame.

We start by loading the required packages. ggplot2 is included in the tidyverse package.

library(tidyverse)

Now let’s load a “cleaned” version of the ADNI dataset that lacks missing values into a variable called adni_c.

adni_c<- read_csv("data/adni_clean.csv")

Plotting with ggplot2

ggplot2 is a plotting package that makes it simple to create complex plots from data in a data frame. It provides a more programmatic interface for specifying what variables to plot, how they are displayed, and general visual properties. Therefore, we only need minimal changes if the underlying data change or if we decide to change from a bar plot to a scatter plot. This syntax helps in creating publication quality plots with minimal amounts of adjustments and tweaking.

ggplot2 functions like data in the ‘long’ format, i.e., a column for every dimension, and a row for every observation. Well-structured data will save you lots of time when making figures with ggplot2

ggplot graphics are built step by step by adding new elements. Adding layers in this fashion allows for extensive flexibility and customization of plots.

To build a ggplot, we will use the following basic template that can be used for different types of plots:

ggplot(data = <DATA>,
       mapping = aes(<MAPPINGS>)) +
<GEOM_FUNCTION>()

Define the data:

Use the ggplot() function and bind the plot to a specific data frame using the data argument

ggplot(data = adni_c)

plot of chunk ggplot-data

The output is an empty plot because R has created a ggplot object with the data, but the user hasn’t specified how to plot it.

Choose x and y values:

Define a mapping (using the aesthetic (aes) function), by selecting the variables to be plotted and specifying how to present them in the graph, e.g. as x/y positions or characteristics such as size, shape, color, etc.

ggplot(data = adni_c,
       mapping = aes(x = Hippocampus,
                     y = WholeBrain))

plot of chunk ggplot-aes

Now that we have specified what to plot on each axis, ggplot can draw the axes, but doesn’t know how to plot the data values. Note that the scales already correspond to the range of the data.

Draw the data:

add ‘geoms’ for a graphical representations of the data in the plot (points, lines, bars). ggplot2 offers many different geoms; we will use some

common ones today, including:

  * `geom_point()` for scatter plots, dot plots, etc.
  * `geom_boxplot()` for, well, boxplots!
  * `geom_line()` for trend lines, time series, etc.

To add a geom to the plot use the + operator. Because we have two continuous variables, let’s use geom_point() first:

ggplot(data = adni_c,
       mapping = aes(x = Hippocampus,
                     y = WholeBrain)) +
  geom_point()

plot of chunk first-ggplot

Now we have a scatterplot!

The + operator

The + in the ggplot2 package is particularly useful because it allows you to modify existing ggplot objects. This means you can easily set up plot templates and conveniently explore different types of plots, so the above plot can also be generated with code like this:

# Assign plot to a variable

adni_plot <- ggplot(data = adni_c,
                       aes(x = Hippocampus,
                           y = WholeBrain))


# Draw the plot
adni_plot +
    geom_point()

plot of chunk first-ggplot-with-plus Notes

# This is the correct syntax for adding layers
adni_plot +
  geom_point()

plot of chunk ggplot-with-plus-position

# This will not add the new layer and will return an error message
adni_plot

plot of chunk ggplot-with-plus-position

+  geom_point()
Error: Cannot use `+.gg()` with a single argument. Did you accidentally put + on a new line?

Challenge 1

Scatter plots can be useful exploratory tools for small datasets. For data sets with large numbers of observations, such as the adni_c data set, overplotting of points can be a limitation of scatter plots. One strategy for handling such settings is to use hexagonal binning of observations. The plot space is tessellated into hexagons. Each hexagon is assigned a color based on the number of observations that fall within its boundaries. To use hexagonal binning with ggplot2, first install the R package hexbin from CRAN:

install.packages("hexbin")
library(hexbin)

Then use the geom_hex() function:

adni_plot +
 geom_hex()

plot of chunk ch1-2

What are the relative strengths and weaknesses of a hexagonal bin plot compared to a scatter plot? Examine the above scatter plot and compare it with the hexagonal bin plot that you created.

Solution

It looks nicer, but its not as granular

Building your plots iteratively

Building plots with ggplot2 is typically an iterative process. We start by defining the dataset we’ll use, lay out the axes, and choose a geom:

ggplot(data = adni_c,
       mapping = aes(x = Hippocampus,
                     y = WholeBrain)) +
  geom_point()

plot of chunk create-ggplot-object

Then, we start modifying this plot to extract more information from it. For instance, we can add transparency (alpha) to avoid overplotting:

ggplot(data = adni_c,
       mapping = aes(x = Hippocampus,
                     y = WholeBrain)) +
    geom_point(alpha = 0.1)

plot of chunk adding-transparency

We can also add colors for all the points:

ggplot(data = adni_c,
       mapping = aes(x = Hippocampus,
                     y = WholeBrain)) +
    geom_point(alpha = 0.1,
               color = "blue")

plot of chunk adding-colors

Or to color each of the patient’s gender in the plot differently, you could use a vector as an input to the argument color. ggplot2 will provide a different color corresponding to different values in the vector. Here is an example where we color with PTGENDER:

ggplot(data = adni_c,
       mapping = aes(x = Hippocampus,
                     y = WholeBrain)) +
    geom_point(alpha = 0.5,
               aes(color = PTGENDER))

plot of chunk color-by-gender-1

Challenge 2

Modify the following code to create a scatter plot that colors the points by values in the APOE column.

ggplot(data = adni_c,
      mapping = aes(x = Hippocampus,
                    y = WholeBrain,
                    color = PTGENDER)) +
   geom_point(alpha = 0.5)

plot of chunk challenge-2 Did you get what you expected?

Solution

ggplot(data = adni_c,
      mapping = aes(x = Hippocampus,
                    y = WholeBrain,
                   color = APOE4)) +
  geom_point(alpha = 0.5)

plot of chunk challenge-2a

APOE is a numeric column, so it maps the color as a gradient. If you want each condition to be a different color, convert it to factor

ggplot(data = adni_c,
      mapping = aes(x = Hippocampus,
                    y = WholeBrain,
                   color = as.factor(APOE4))) +
  geom_point(alpha = 0.5)

plot of chunk challenge-2ab

Boxplot

We can use boxplots to visualize the distribution of whole brain volume within each gender:

ggplot(data = adni_c,
       mapping = aes(x = PTGENDER,
                     y = WholeBrain)) +
    geom_boxplot()

plot of chunk boxplot

By adding points to boxplot, we can have a better idea of the number of measurements and of their distribution:

ggplot(data = adni_c,
       mapping = aes(x = PTGENDER,
                     y = WholeBrain)) +
    geom_boxplot()+
  geom_jitter(color = "tomato")

plot of chunk boxplot-with-points

Notice how the boxplot layer is behind the jitter layer? What do you need to change in the code to put the boxplot in front of the points such that it’s not hidden?

Challenge

Notice how the boxplot layer is behind the jitter layer in the previous plot? What do you need to change in the code to put the boxplot in front of the points such that it’s not hidden?

Solution

ggplot(data = adni_c, mapping = aes(x = PTGENDER, y = WholeBrain)) + geom_jitter(color = “tomato”) + geom_boxplot() ```

Colors and multiple geoms

We can specify how to color the points on the plot in two places:

  1. In the geom_XX() function, as we’ve seen in the above examples. This option only affects the geom that you put the color argument in.
  2. In the ggplot() function. Parameters specified in ggplot will affect the entire plot.

ALL geom layers and the mapping will be determined by the x- and y-axis set up in aes(). Let’s see an example.

The following plot colors the jittered dots by PTGENDER. The boxes remain black and white.

ggplot(data = adni_c,
       mapping = aes(x = PTGENDER,
                     y = WholeBrain)) +
   geom_jitter(aes(color = PTGENDER))+
  geom_boxplot()

plot of chunk boxplot-with-geom-color

Now let’s see what the plot looks like when we move the color argument to the ggplot function.

ggplot(data = adni_c,
       mapping = aes(x = PTGENDER,
                     y = WholeBrain,
                     color = PTGENDER)) +
   geom_jitter()+
   geom_boxplot()

plot of chunk boxplot-with-ggplot-color

Now the box outlines are also colored by PTGENDER and the lines blend into the jitter.

Notice that we can change the geom layer and colors will be still determined by PTGENDER

ggplot(data = adni_c,
       mapping = aes(x = PTGENDER,
                     y = WholeBrain,
                     color = PTGENDER)) +
  geom_boxplot()+
    geom_point()

plot of chunk color-by-educ-3

Plotting time series data

Let’s calculate the mean whole brain volume by age for each APOE4 status group. First we need to group the data and count records within each group. However, we need to reshape the data first using what we learned with dplyr, We need a data frame with a row for each APOE4 AGE combination, and columns for the mean (mean_hippocampus) and standard deviation (sd_hippocampus) of hippocampus volume.

APOE4 AGE mean_hippocampus sd_hippocampus
0 70
1 70
2 70
0 71
1 71
2 71
adni_time <- adni_c%>%
  group_by(APOE4, AGE)%>%
  summarize(mean_hippocampus = mean(Hippocampus),
            sd_hippocampus = sd(Hippocampus))

adni_time
# A tibble: 103 x 4
# Groups:   APOE4 [3]
   APOE4   AGE mean_hippocampus sd_hippocampus
   <dbl> <dbl>            <dbl>          <dbl>
 1     0    54            8004             NA 
 2     0    55            5925.           352.
 3     0    56            7211.          1049.
 4     0    57            6713.          1589.
 5     0    58            7493.           918.
 6     0    59            8141           1406.
 7     0    60            8260.           825.
 8     0    61            8286.           921.
 9     0    62            7730.          1512.
10     0    63            7701.           681.
# … with 93 more rows

Time series data can be visualized as a line plot with age on the x axis and mean Hippocampus volume on the y axis:

ggplot(data = adni_time,
       mapping = aes(x = AGE,
                     y = mean_hippocampus)) +
     geom_line()

plot of chunk first-time-series

Unfortunately, this does not work because we plotted data for all three APOE4 categories together. We need to tell ggplot to draw a line for each APOE4 by modifying the aesthetic function to include group = APOE4:

ggplot(data = adni_time,
       mapping = aes(x = AGE,
                     y = mean_hippocampus,
                     group = APOE4)) +
     geom_line()

plot of chunk time-series-by-apoe4

We will be able to distinguish APOE4 groups in the plot if we add colors (using color also automatically groups the data). Note that we’re using both group and color here.

ggplot(data = adni_time,
       mapping = aes(x = AGE,
                     y = mean_hippocampus,
                     group = APOE4,
                     color = as.factor(APOE4))) +
     geom_line()

plot of chunk time-series-with-colors

In reality, you only need color and it looks the same

ggplot(data = adni_time,
       mapping = aes(x = AGE,
                     y = mean_hippocampus,
                     color = as.factor(APOE4))) +
     geom_line()

plot of chunk time-series-with-colors-2 However, occasionally using color alone won’t work. If this happens to you, try adding group back and see if it helps.

It looks like there might be a relationship between APOE allele number and hippocampus volume by age. Let’s see what the variation in the dat looks like by adding error bars.

Adding error bars

ggplot(data = adni_time,
       mapping = aes(x = AGE,
                     y = mean_hippocampus,
                     #group = APOE4,
                     color = as.factor(APOE4))) +
  geom_line()+
  geom_errorbar(aes(ymin = mean_hippocampus-sd_hippocampus,
                    ymax = mean_hippocampus+sd_hippocampus))

plot of chunk time-series-with-error-bars

Unfortunately, the variation is larger than the effect from the look of it, so the relationship is weak.

Faceting

ggplot2 has a special technique called faceting that allows the user to split one plot into multiple plots based on a variable/feature included in the dataset. We will use it to make a time series plot for each APOE4 group:

ggplot(data = adni_time,
       mapping = aes(x = AGE,
                     y = mean_hippocampus)) +
     geom_line() +
    facet_wrap(~ APOE4)

plot of chunk first-facet

What if we want to look at the effect of PTGENDER in each APOE4 group? We need to add another variable to the adni_time data frame: PTGENDER.

adni_time <- adni_c%>%
  group_by(APOE4, AGE, PTGENDER)%>%
  summarize(mean_hippocampus = mean(Hippocampus),
            sd_hippocampus = sd(Hippocampus))

adni_time
# A tibble: 187 x 5
# Groups:   APOE4, AGE [103]
   APOE4   AGE PTGENDER mean_hippocampus sd_hippocampus
   <dbl> <dbl> <chr>               <dbl>          <dbl>
 1     0    54 Male                8004             NA 
 2     0    55 Female              5925.           352.
 3     0    56 Female              6340            471.
 4     0    56 Male                7833.           890.
 5     0    57 Female              5748.          1245.
 6     0    57 Male                8256.           155.
 7     0    58 Female              7447.           269.
 8     0    58 Male                7518.          1134.
 9     0    59 Female              6917.           289.
10     0    59 Male                8928.          1261.
# … with 177 more rows

We can now make the faceted plot by splitting further by PTGENDER using color (within a single plot).

ggplot(data = adni_time,
       mapping = aes(x = AGE,
                     y = mean_hippocampus,
                     color = PTGENDER)) +
     geom_line() +
    facet_wrap(~ APOE4)

plot of chunk facet-by-apoe4-and-age

Usually plots with white background look more readable when printed. We can set the background to white using the function theme_bw(). Additionally, you can remove the grid:

ggplot(data = adni_time,
       mapping = aes(x = AGE,
                     y = mean_hippocampus,
                     color = PTGENDER)) +
     geom_line() +
    facet_wrap(~ APOE4)+
     theme_bw() +
     theme(panel.grid = element_blank())

plot of chunk facet-by-apoe4-and-age-white-bg

ggplot2 themes

In addition to theme_bw(), which changes the plot background to white, ggplot2 comes with several other themes which can be useful to quickly change the look of your visualization. The complete list of themes is available at https://ggplot2.tidyverse.org/reference/ggtheme.html. theme_minimal() and theme_light() are popular, and theme_void() can be useful as a starting point to create a new hand-crafted theme.

The ggthemes package provides a wide variety of options (including an Excel 2003 theme). The ggplot2 extensions website provides a list of packages that extend the capabilities of ggplot2, including additional themes.

Challenge 3

Use what you just learned to create a plot that depicts how the average whole brain volume of each APOE4 group changes by age. Use dplyr functions to create a new data.frame called age_wholebrain that contains a new column called avg_wholebrain for each APOE4 group and age. Then create a plot that shows the differences in avg_wholebrain values for each group at each age.

Solution

age_wholebrain <- adni_c %>%
                     group_by(AGE, APOE4) %>%
                     summarize(avg_wholebrain = mean(WholeBrain))

ggplot(data = age_wholebrain,
       mapping = aes(x=AGE,
                     y=avg_wholebrain)) +
   geom_line() +
   facet_wrap(~ APOE4) +
   theme_bw()

plot of chunk average-volume-time-series

The facet_wrap geometry extracts plots into an arbitrary number of dimensions to allow them to cleanly fit on one page. On the other hand, the facet_grid geometry allows you to explicitly specify how you want your plots to be arranged via formula notation (rows ~ columns; a . can be used as a placeholder that indicates only one row or column).

Let’s modify the previous plot to lay out the plot by APOE4 status and PTGENDER using facet_grid. This function takes two categorical variables in the format x~y as arguments and makes columns of plots based on x, and rows based on y.

# One column, facet by rows

ggplot(data = adni_time,
       mapping = aes(x = AGE,
                     y = mean_hippocampus)) +
    geom_line() +
    facet_grid(APOE4 ~ PTGENDER)

plot of chunk average-wholebrain-gender-facet-apoe4-rows

Challenge 4

Take a look at the ggplot2 cheat sheet, and think of ways you could improve the plot.

Customization

Now, let’s change names of axes to something more informative than ‘avg_wholebrain’ and add a title to the figure:

ggplot(data = adni_time,
       mapping = aes(x = AGE,
                     y = mean_hippocampus,
                     color = PTGENDER)) +
     geom_line() +
    facet_wrap(~ APOE4)+
    labs(title = "Average Whole Brain Volume by Age",
         x = "Age",
         y = "Average Whole Brain Volume") +
    theme_bw()

plot of chunk average-wb-age-apoe4-gender

The axes have more informative names, but their readability can be improved by increasing the font size:

ggplot(data = adni_time,
       mapping = aes(x = AGE,
                     y = mean_hippocampus,
                     color = PTGENDER)) +
     geom_line() +
    facet_wrap(~ APOE4)+
    labs(title = "Average Whole Brain Volume by Age",
         x = "Age",
         y = "Average Whole Brain Volume") +
    theme_bw()+
    theme(text=element_text(size = 16))

plot of chunk average-wb-age-apoe4-gender-with-right-labels-xfont-size

Note that it is also possible to change the fonts of your plots. If you are on Windows, you may have to install the extrafont package, and follow the instructions included in the README for this package.

ggplot(data = adni_time,
       mapping = aes(x = AGE,
                     y = mean_hippocampus,
                     color = PTGENDER)) +
  geom_line() +
  facet_wrap(~ APOE4)+
  theme_bw()+
  theme(axis.text.x = element_text(colour = "grey20",
                                               size = 12),
                    axis.text.y = element_text(colour = "grey20",
                                     size = 12),
                    text = element_text(size = 16))

plot of chunk wb-educ-with smaller axis labels

If you like the changes you created better than the default theme, you can save them as an object to be able to easily apply them to other plots you may create:

grey_theme <- theme_bw()+
  theme(axis.text.x = element_text(colour = "grey20",
                                   size = 12),
        axis.text.y = element_text(colour = "grey20",
                                   size = 12),
        text = element_text(size = 16))


ggplot(data = adni_c,
       mapping = aes(x = PTGENDER,
                     y = WholeBrain)) +
  geom_boxplot() +
  grey_theme

plot of chunk wb-educ-with-right-labels-xfont-orientation

Challenge

With all of this information in hand, please take another five minutes to either improve one of the plots generated in this exercise or create a beautiful graph of your own. Use the RStudio ggplot2 cheat sheet for inspiration. Here are some ideas:

Arranging and exporting plots

Faceting is a great tool for splitting one plot into multiple plots, but sometimes you may want to produce a single figure that contains multiple plots using different variables or even different data frames. The gridExtra package allows us to combine separate ggplots into a single figure using grid.arrange():

install.packages("gridExtra")
library(gridExtra)

my_boxplot <- ggplot(data = adni_c,
       mapping = aes(x = PTGENDER,
                     y = WholeBrain)) +
    geom_boxplot() +
    xlab("Gender") +
    ylab("Whole Brain Volume") +
    scale_y_log10()

my_lineplot <- ggplot(data = adni_time,
                      mapping = aes(x = AGE,
                                    y = mean_hippocampus,
                                    group = APOE4)) +
  geom_line(aes(color = as.factor(APOE4)))+
  xlab("Age") +
  ylab("Average Whole Brain Volume")


grid.arrange(my_boxplot, my_lineplot ,
             ncol = 2,
             widths = c(4, 10))

plot of chunk gridarrange-example

In addition to the ncol and nrow arguments, used to make simple arrangements, there are tools for constructing more complex layouts.

After creating your plot, you can save it to a file in your favorite format. The Export tab in the Plot pane in RStudio will save your plots at low resolution, which will not be accepted by many journals and will not scale well for posters.

Instead, use the ggsave() function, which allows you easily change the dimension and resolution of your plot by adjusting the appropriate arguments (width, height and dpi).

Make sure you have the figs/ folder in your working directory.

my_plot <- grid.arrange(my_boxplot, my_lineplot ,
             ncol = 2,
             widths = c(4, 10))

plot of chunk ggsave-example

ggsave("figs/grid.png", my_plot, width = 15, height = 10)

Note: The parameters width and height also determine the font size in the saved plot.

Key Points