Extra plotting with ggplot2

ggplot2 is an great package for making pretty plots.

This notebook will only descripe ggplot2 very shortly, as there are other excellent resources descibing the details:

Cheatsheet - 2-page pdf with a summary of ggplot2:

This browser does not support PDFs. Please download the PDF to view it: Download PDF.

In [1]:
# Load ggplot2
library(ggplot2)
In [2]:
# Data
data(mtcars)

ggplot2 components

The backbone is created with the ggplot function, where we input our data.frame:

In [3]:
ggplot(mtcars)

Aesthetics

Usually we would also add the aesthetics (aes), which tells which variables should be on the x-axes, on the y-axis, and if any variables should be used to indicate color, shape, or linetype.

In [4]:
ggplot(mtcars, aes(x = hp, y = disp, color = gear))

Geometrics

This however does not draw the plot. We need to add geometrics (geom), which tells ggplot2 how to plot the data:

In [5]:
ggplot(mtcars, aes(x = hp, y = disp, color = gear)) +
    geom_point()

Themes

We can then add a theme:

In [6]:
ggplot(mtcars, aes(x = hp, y = disp, color = gear)) +
    geom_point() +
    theme_bw()

Scales

We can add scales:

In [7]:
ggplot(mtcars, aes(x = hp, y = disp, color = gear)) +
    geom_point() +
    theme_bw() +
    scale_x_continuous(name="HP", breaks=seq(0,350,50))

Labels

We can add labels:

In [8]:
ggplot(mtcars, aes(x = hp, y = disp, color = gear)) +
    geom_point() +
    theme_bw() +
    scale_x_continuous(name="HP", breaks=seq(0,350,50)) +
    ylab("New label") +
    ggtitle("My title")

Facetting

We can facet the plot, by splitting it by a variable:

In [9]:
ggplot(mtcars, aes(x = hp, y = disp, color = gear)) +
    geom_point() +
    theme_bw() +
    scale_x_continuous(name="HP", breaks=seq(0,350,50)) +
    ylab("New label") +
    ggtitle("My title") +
    facet_grid(.~cyl)

Regressions

We can add a linear regression:

In [10]:
ggplot(mtcars, aes(x = hp, y = disp, color = gear)) +
    geom_point() +
    theme_bw() +
    scale_x_continuous(name="HP", breaks=seq(0,350,50)) +
    ylab("New label") +
    ggtitle("My title") +
    facet_grid(.~cyl) +
    stat_smooth(method = "lm")
`geom_smooth()` using formula 'y ~ x'