R for Applied Economists: Session 4

Today’s plan

Graphing

Introduction

As is so often the case, there are multiple packages for doing graphs in R. There is base functionality, which hardly anyone seems to use, and then two main contenders: ggplot2 and lattice. Here’s an introduction to ggplot2.

library(ggplot2)

mycars <- mtcars
mycars$car <- rownames(mycars)
rownames(mycars) <- NULL

There are three components to any ggplot call:

Basic examples

Plot points mpg (x-axis) vs wt (y-axis)

ggplot(data = mycars, aes(x = mpg, y = wt)) +
  geom_point()

Add a lowess smoother:

ggplot(mycars, aes(x = mpg, y = wt)) +
    geom_point() +
    geom_smooth()

Or labels:

ggplot(mycars, aes(x = mpg, y = wt)) +
    geom_point()  +
    geom_text(aes(label = car))

(Use geom_text_repel from the ggrepel package to improve the labelling)

Provide options to geom functions:

ggplot(mycars, aes(x = mpg, y = wt)) + 
        geom_point(color="royalblue", size = 2)  +
        geom_smooth(method=lm, se = FALSE, color="grey")

Set aesthetic mappings for individual geoms, e.g. color:

ggplot(mycars,  aes(x = mpg, y = wt)) + 
        geom_point(aes(color=qsec)) + 
        geom_smooth(method=lm, se = FALSE, color="red")

.. or size:

ggplot(mycars,  aes(x = mpg, y = wt)) + 
        geom_point(aes(size=qsec)) + 
        geom_smooth(method=lm, se = FALSE, color="red")

.. or shape (having turned “am”" into a factor):

ggplot(mycars,  aes(x = mpg, y = wt)) + 
        geom_point(aes(shape=factor(am)),size=3) + 
        geom_smooth(method=lm, se = FALSE, color="red")