Intro to ggplot2

Max Joseph & Joe Mihaljevic
Oct 1 2013

What is ggplot2?

R package for visualization based on the grammar of graphics.

Developed primarily by Hadley Wickham

Grammar of graphics

A syntactic and conceptual framework for producing graphics.

Implementation in ggplot2

One syntactic framework for many plots

^ major advantage over base graphics

Elements

Plots emerge from layered components:

  • aesthetics (roles variables play)
  • geometric objects
  • scales
  • stats
  • facets

Getting started

install.packages("ggplot2")
require(ggplot2)

Data

ggplot2 uses data frames

# load data
data(msleep)

# check object class
class(msleep)
[1] "data.frame"

Scatterplot

p <- ggplot(msleep, aes(x=bodywt, y=brainwt)) + geom_point()
p

plot of chunk unnamed-chunk-5

Aesthetics & geoms

alt <- ggplot(msleep) + geom_point(aes(x=bodywt, y=brainwt))
alt

plot of chunk unnamed-chunk-8

Axis scaling

p <- p + scale_y_log10() + scale_x_log10()
p

plot of chunk unnamed-chunk-11

Classic theme

p <- p + theme_classic()
p

plot of chunk unnamed-chunk-14

Smoothing

p + stat_smooth()

plot of chunk unnamed-chunk-15

OLS regression line

p <- p + stat_smooth(method="lm")
p

plot of chunk unnamed-chunk-16

Faceting

p + facet_wrap(~vore)

plot of chunk unnamed-chunk-18

Color

p + geom_point(aes(color=vore), size=3)