Materials and setup

Laptop users: You should have R installed; if not:

  1. Open a web browser and go to http://cran.r-project.org and download and install it

  2. Also helpful to install RStudio (download from http://rstudio.com)

  3. In R, type install.packages("tidyverse") to install a suite of usefull packages including ggplot2

Everyone: Download workshop materials:

  1. Download materials from http://tutorials.iq.harvard.edu/R/Rgraphics.zip

  2. Extract the zip file containing the materials to your desktop

Workshop Overview

Class Structure and Organization:

  • Ask questions at any time. Really!
  • Collaboration is encouraged
  • This is your class! Special requests are encouraged

This is an intermediate R course:

  • Assumes working knowledge of R
  • Relatively fast-paced
  • Focus is on ggplot2 graphics–other packages will not be covered

Starting At The End

My goal: by the end of the workshop you will be able to reproduce this graphic from the Economist:

img

img

Why ggplot2?

Advantages of ggplot2

  • consistent underlying grammar of graphics (Wilkinson, 2005)
  • plot specification at a high level of abstraction
  • very flexible
  • theme system for polishing plot appearance
  • mature and complete graphics system
  • many users, active mailing list

That said, there are some things you cannot (or should not) do With ggplot2:

  • 3-dimensional graphics (see the rgl package)
  • Graph-theory type graphs (nodes/edges layout; see the igraph package)
  • Interactive graphics (see the ggvis package)

What Is The Grammar Of Graphics?

The basic idea: independently specify plot building blocks and combine them to create just about any kind of graphical display you want. Building blocks of a graph include:

  • data
  • aesthetic mapping
  • geometric object
  • statistical transformations
  • scales
  • coordinate system
  • position adjustments
  • faceting

Setup: install the tidyverse package

The ggplot2 packages is included in a popular collection of packages called “the tidyverse”. Take a moment to ensure that it is installed, and that we have attached the ggplot2 package.

## ── Attaching packages ────────────────────────────────── tidyverse 1.2.1 ──
## ✔ ggplot2 3.0.0     ✔ purrr   0.2.5
## ✔ tibble  1.4.2     ✔ dplyr   0.7.6
## ✔ tidyr   0.8.1     ✔ stringr 1.3.1
## ✔ readr   1.1.1     ✔ forcats 0.3.0
## ── Conflicts ───────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()

Example Data: Housing prices

Let’s look at housing prices.

## Parsed with column specification:
## cols(
##   State = col_character(),
##   region = col_character(),
##   Date = col_double(),
##   Home.Value = col_integer(),
##   Structure.Cost = col_integer(),
##   Land.Value = col_integer(),
##   Land.Share..Pct. = col_double(),
##   Home.Price.Index = col_double(),
##   Land.Price.Index = col_double(),
##   Year = col_integer(),
##   Qrtr = col_integer()
## )
## # A tibble: 6 x 5
##   State region  Date Home.Value Structure.Cost
##   <chr> <chr>  <dbl>      <int>          <int>
## 1 AK    West   2010.     224952         160599
## 2 AK    West   2010.     225511         160252
## 3 AK    West   2010.     225820         163791
## 4 AK    West   2010      224994         161787
## 5 AK    West   2008      234590         155400
## 6 AK    West   2008.     233714         157458

ggplot2 VS Base Graphics

Compared to base graphics, ggplot2

  • is more verbose for simple / canned graphics
  • is less verbose for complex / custom graphics
  • does not have methods (data should always be in a data.frame)
  • uses a different system for adding plot elements

ggplot2 VS Base for simple graphs

Base graphics histogram example:

ggplot2 histogram example:

## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Geometric Objects And Aesthetics

Aesthetic Mapping

In ggplot land aesthetic means “something you can see”. Examples include:

  • position (i.e., on the x and y axes)
  • color (“outside” color)
  • fill (“inside” color)
  • shape (of points)
  • linetype
  • size

Each type of geom accepts only a subset of all aesthetics–refer to the geom help pages to see what mappings each geom accepts. Aesthetic mappings are set with the aes() function.

Geometic Objects (geom)

Geometric objects are the actual marks we put on a plot. Examples include:

  • points (geom_point, for scatter plots, dot plots, etc)
  • lines (geom_line, for time series, trend lines, etc)
  • boxplot (geom_boxplot, for, well, boxplots!)

A plot must have at least one geom; there is no upper limit. You can add a geom to a plot using the + operator

You can get a list of available geometric objects using the code below:

or simply type geom_<tab> in any good R IDE (such as Rstudio or ESS) to see a list of functions starting with geom_.

Points (Scatterplot)

Now that we know about geometric objects and aesthetic mapping, we can make a ggplot. geom_point requires mappings for x and y, all others are optional.

Lines (Prediction Line)

A plot constructed with ggplot can have more than one geom. In that case the mappings established in the ggplot() call are plot defaults that can be added to or overridden. Our plot could use a regression line:

Smoothers

Not all geometric objects are simple shapes–the smooth geom includes a line and a ribbon.

## `geom_smooth()` using method = 'loess' and formula 'y ~ x'

Text (Label Points)

Each geom accepts a particualar set of mappings;for example geom_text() accepts a labels mapping.

Aesthetic Mapping VS Assignment

Note that variables are mapped to aesthetics with the aes() function, while fixed aesthetics are set outside the aes() call. This sometimes leads to confusion, as in this example:

Mapping Variables To Other Aesthetics

Other aesthetics are mapped in the same way as x and y in the previous example.

## Warning: Removed 1 rows containing missing values (geom_point).

Exercise I

The data for the exercises is available in the dataSets/EconomistData.csv file. Read it in with

## Parsed with column specification:
## cols(
##   Country = col_character(),
##   HDI.Rank = col_integer(),
##   HDI = col_double(),
##   CPI = col_double(),
##   Region = col_character()
## )

Original sources for these data are http://www.transparency.org/content/download/64476/1031428 http://hdrstats.undp.org/en/indicators/display_cf_xls_indicator.cfm?indicator_id=103106&lang=en

These data consist of Human Development Index and Corruption Perception Index scores for several countries.

  1. Create a scatter plot with CPI on the x axis and HDI on the y axis.
  2. Color the points blue.
  3. Map the color of the the points to Region.
  4. Make the points bigger by setting size to 2
  5. Map the size of the points to HDI.Rank

Exercise I prototype :prototype:

  1. Create a scatter plot with CPI on the x axis and HDI on the y axis.

  1. Color the points in the previous plot blue.

  1. Color the points in the previous plot according to Region.

  1. Make the points bigger by setting size to 2

  1. Make the points bigger by setting size to 2

Statistical Transformations

Statistical Transformations

Some plot types (such as scatterplots) do not require transformations–each point is plotted at x and y coordinates equal to the original value. Other plots, such as boxplots, histograms, prediction lines etc. require statistical transformations:

  • for a boxplot the y values must be transformed to the median and 1.5(IQR)
  • for a smoother smother the y values must be transformed into predicted values

Each geom has a default statistic, but these can be changed. For example, the default statistic for geom_bar is stat_bin:

## function (mapping = NULL, data = NULL, stat = "bin", position = "stack", 
##     ..., binwidth = NULL, bins = NULL, na.rm = FALSE, show.legend = NA, 
##     inherit.aes = TRUE) 
## NULL
## function (mapping = NULL, data = NULL, geom = "bar", position = "stack", 
##     ..., binwidth = NULL, bins = NULL, center = NULL, boundary = NULL, 
##     breaks = NULL, closed = c("right", "left"), pad = FALSE, 
##     na.rm = FALSE, show.legend = NA, inherit.aes = TRUE) 
## NULL

Setting Statistical Transformation Arguments

Arguments to stat_ functions can be passed through geom_ functions. This can be slightly annoying because in order to change it you have to first determine which stat the geom uses, then determine the arguments to that stat.

For example, here is the default histogram of Home.Value:

## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

can change it by passing the binwidth argument to the stat_bin function:

Changing The Statistical Transformation

Sometimes the default statistical transformation is not what you need. This is often the case with pre-summarized data:

##    State Home.Value
## 1     AK  147385.14
## 2     AL   92545.22
## 3     AR   82076.84
## 4     AZ  140755.59
## 5     CA  282808.08
## 6     CO  158175.99
## 46    VA  155391.44
## 47    VT  132394.60
## 48    WA  178522.58
## 49    WI  108359.45
## 50    WV   77161.71
## 51    WY  122897.25
## Error: stat_count() must not be used with a y aesthetic.

What is the problem with the previous plot? Basically we take binned and summarized data and ask ggplot to bin and summarize it again (remember, geom_bar defaults to stat = stat_count); obviously this will not work. We can fix it by telling geom_bar to use a different statistical transformation function:

Exercise II

  1. Re-create a scatter plot with CPI on the x axis and HDI on the y axis (as you did in the previous exercise).
  2. Overlay a smoothing line on top of the scatter plot using geom_smooth.
  3. Overlay a smoothing line on top of the scatter plot using geom_smooth, but use a linear model for the predictions. Hint: see ?stat_smooth.
  4. Overlay a smoothing line on top of the scatter plot using geom_line. Hint: change the statistical transformation.
  5. BONUS: Overlay a smoothing line on top of the scatter plot using the default loess method, but make it less smooth. Hint: see ?loess.

Exercise II prototype :prototype:

  1. Re-create a scatter plot with CPI on the x axis and HDI on the y axis (as you did in the previous exercise).

  1. Overlay a smoothing line on top of the scatter plot using geom_smooth
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'

  1. Overlay a smoothing line on top of the scatter plot using geom_smooth, but use a linear model for the predictions. Hint: see ?stat_smooth.

  1. Overlay a loess (method = “loess”) smoothling line on top of the scatter plot using geom_line. Hint: change the statistical transformation.

  1. BONUS: Overlay a smoothing line on top of the scatter plot using the loess method, but make it less smooth. Hint: see ?loess.
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'

Scales

Scales: Controlling Aesthetic Mapping

Aesthetic mapping (i.e., with aes()) only says that a variable should be mapped to an aesthetic. It doesn’t say how that should happen. For example, when mapping a variable to shape with aes(shape = x) you don’t say what shapes should be used. Similarly, aes(color = z) doesn’t say what colors should be used. Describing what colors/shapes/sizes etc. to use is done by modifying the corresponding scale. In ggplot2 scales include

  • position
  • color and fill
  • size
  • shape
  • line type

Scales are modified with a series of functions using a scale_<aesthetic>_<type> naming scheme. Try typing scale_<tab> to see a list of scale modification functions.

Common Scale Arguments

The following arguments are common to most scales in ggplot2:

  • name: the first argument gives the axis or legend title
  • limits: the minimum and maximum of the scale
  • breaks: the points along the scale where labels should appear
  • labels: the labels that appear at each break

Specific scale functions may have additional arguments; for example, the scale_color_continuous function has arguments low and high for setting the colors at the low and high end of the scale.

Using different color scales

ggplot2 has a wide variety of color scales; here is an example using scale_color_gradient2 to interpolate between three different colors.

Available Scales

  • Partial combination matrix of available scales
Scale Types Examples
scale_color_ identity scale_fill_continuous
scale_fill_ manual scale_color_discrete
scale_size_ continuous scale_size_manual
discrete scale_size_discrete
scale_shape_ discrete scale_shape_discrete
scale_linetype_ identity scale_shape_manual
manual scale_linetype_discrete
scale_x_ continuous scale_x_continuous
scale_y_ discrete scale_y_discrete
reverse scale_x_log
log scale_y_reverse
date scale_x_date
datetime scale_y_datetime

Note that in RStudio you can type scale_ followed by TAB to get the whole list of available scales.

Exercise III

  1. Create a scatter plot with CPI on the x axis and HDI on the y axis. Color the points to indicate region.
  2. Modify the x, y, and color scales so that they have more easily-understood names (e.g., spell out “Human development Index” instead of “HDI”).
  3. Modify the color scale to use specific values of your choosing. Hint: see ?scale_color_manual.

Faceting

Faceting

  • Faceting is ggplot2 parlance for small multiples
  • The idea is to create separate graphs for subsets of data
  • ggplot2 offers two functions for creating small multiples:
    1. facet_wrap(): define subsets as the levels of a single grouping variable
    2. facet_grid(): define subsets as the crossing of two grouping variables
  • Facilitates comparison among plots, not just of geoms within a plot

What is the trend in housing prices in each state?

  • Start by using a technique we already know–map State to color:

There are two problems here–there are too many states to distinguish each one by color, and the lines obscure one another.

Faceting to the rescue

We can remedy the deficiencies of the previous plot by faceting by state rather than mapping state to color.

There is also a facet_grid() function for faceting in two dimensions.

Themes

Themes

The ggplot2 theme system handles non-data plot elements such as

  • Axis labels
  • Plot background
  • Facet label backround
  • Legend appearance

Built-in themes include:

  • theme_gray() (default)
  • theme_bw()
  • theme_classc()

Overriding theme defaults

Specific theme elements can be overridden using theme(). For example:

All theme options are documented in ?theme.

The #1 FAQ

Map Aesthetic To Different Columns

The most frequently asked question goes something like this: I have two variables in my data.frame, and I’d like to plot them as separate points, with different color depending on which variable it is. How do I do that?

Putting It All Together

Challenge: Recreate This Economist Graph

<images/Economist1.pdf>

Graph source: http://www.economist.com/node/21541178

Building off of the graphics you created in the previous exercises, put the finishing touches to make it as close as possible to the original economist graph.

Challenge Solution :prototype:

Lets start by creating the basic scatter plot, then we can make a list of things that need to be added or changed. The basic plot loogs like this:

## Parsed with column specification:
## cols(
##   Country = col_character(),
##   HDI.Rank = col_integer(),
##   HDI = col_double(),
##   CPI = col_double(),
##   Region = col_character()
## )

To complete this graph we need to:

  • [ ] add a trend line
  • [ ] change the point shape to open circle
  • [ ] change the order and labels of Region
  • [ ] label select points
  • [ ] fix up the tick marks and labels
  • [ ] move color legend to the top
  • [ ] title, label axes, remove legend title
  • [ ] theme the graph with no vertical guides
  • [ ] add model R2 (hard)
  • [ ] add sources note (hard)
  • [ ] final touches to make it perfect (use image editor for this)

Adding the trend line

Adding the trend line is not too difficult, though we need to guess at the model being displyed on the graph. A little bit of trial and error leads to

Notice that we put the geom_line layer first so that it will be plotted underneath the points, as was done on the original graph.

Labelling points

This one is tricky in a couple of ways. First, there is no attribute in the data that separates points that should be labelled from points that should not be. So the first step is to identify those points.

Now we can label these points using geom_text, like this:

This more or less gets the information across, but the labels overlap in a most unpleasing fashion. We can use the ggrepel package to make things better, but if you want perfection you will probably have to do some hand-adjustment.

Change the region labels and order

Thinkgs are starting to come together. There are just a couple more things we need to add, and then all that will be left are themeing changes.

Comparing our graph to the original we notice that the labels and order of the Regions in the color legend differ. To correct this we need to change both the labels and order of the Region variable. We can do this with the factor function.

Now when we construct the plot using these data the order should appear as it does in the original.

Add model R2 and source note

The last bit of information that we want to have on the graph is the variance explained by the model represented by the trend line. Lets fit that model and pull out the R2 first, then think about how to get it onto the graph.

OK, now that we’ve calculated the values, let’s think about how to get them on the graph. ggplot2 has an annotate function, but this is not convenient for adding elements outside the plot area. The grid package has nice functions for doing this, so we’ll use those.

And here it is, our final version!

png(file = "images/econScatter10.png", width = 700, height = 500)
p <- ggplot(dat,
            mapping = aes(x = CPI, y = HDI)) +
  geom_smooth(mapping = aes(linetype = "r2"),
              method = "lm",
              formula = y ~ x + log(x), se = FALSE,
              color = "red") +
  geom_point(mapping = aes(color = Region),
             shape = 1,
             size = 4,
             stroke = 1.5) +
  geom_text_repel(mapping = aes(label = Country, alpha = labels),
                  color = "gray20",
                  data = transform(dat,
                                   labels = Country %in% c("Russia",
                                                           "Venezuela",
                                                           "Iraq",
                                                           "Mayanmar",
                                                           "Sudan",
                                                           "Afghanistan",
                                                           "Congo",
                                                           "Greece",
                                                           "Argentinia",
                                                           "Italy",
                                                           "Brazil",
                                                           "India",
                                                           "China",
                                                           "South Africa",
                                                           "Spain",
                                                           "Cape Verde",
                                                           "Bhutan",
                                                           "Rwanda",
                                                           "France",
                                                           "Botswana",
                                                           "France",
                                                           "US",
                                                           "Germany",
                                                           "Britain",
                                                           "Barbados",
                                                           "Japan",
                                                           "Norway",
                                                           "New Zealand",
                                                           "Sigapore"))) +
  scale_x_continuous(name = "Corruption Perception Index, 2011 (10=least corrupt)",
                     limits = c(1.0, 10.0),
                     breaks = 1:10) +
  scale_y_continuous(name = "Human Development Index, 2011 (1=best)",
                     limits = c(0.2, 1.0),
                     breaks = seq(0.2, 1.0, by = 0.1)) +
  scale_color_manual(name = "",
                     values = c("#24576D",
                                "#099DD7",
                                "#28AADC",
                                "#248E84",
                                "#F2583F",
                                "#96503F"),
                     guide = guide_legend(nrow = 1, order=1)) +
  scale_alpha_discrete(range = c(0, 1),
                       guide = FALSE) +
  scale_linetype(name = "",
                 breaks = "r2",
                 labels = list(bquote(R^2==.(mR2))),
                 guide = guide_legend(override.aes = list(linetype = 1, size = 2, color = "red"), order=2)) +
  ggtitle("Corruption and human development") +
  labs(caption="Sources: Transparency International; UN Human Development Report") +
  theme_bw() +
  theme(panel.border = element_blank(),
        panel.grid = element_blank(),
        panel.grid.major.y = element_line(color = "gray"),
        text = element_text(color = "gray20"),
        axis.title.x = element_text(face="italic"),
        axis.title.y = element_text(face="italic"),
        legend.position = "top",
        legend.direction = "horizontal",
        legend.box = "horizontal",
        legend.text = element_text(size = 12),
        plot.caption = element_text(hjust=0),
        plot.title = element_text(size = 16, face = "bold"))
## Warning: Using alpha for a discrete variable is not advised.
## png 
##   2

Comparing it to the original suggests that we’ve got most of the important elements.

Wrap-up

Help Us Make This Workshop Better!

Additional resources