Plotting with ggplot2

First, get ggplot2 from CRAN

install.packages("ggplot2")

and load it

library(ggplot2)
theme_set(theme_bw())

For illustration purposes, we load a data set from another package. In this exercise sheet we are going to produce our own data.frames.

data(Oxboys, package = "nlme")
mydata <- subset(Oxboys, Subject %in% as.character(1:9))

The data set contains columns Subject, age, height and Occasion. The standard procedure to produce a plot with ggplot2 is the following

  1. Generate the structure of the plot: ggplot(data, aes(x = ..., y = ..., ...)) from a data set data and a mapping returned by the aes() function.
  2. Add graphical elements to the plot: ... + geom_line() + geom_point() + ...

Graphical elements can be lines, points, bars, etc. but also instructions how to distribute plots, e.g., facet_wrap() or facet_grid to arrange the plot in subplots.

We use the Oxboys dataset to generate some example plots

Grouping of different occasions in one plot

ggplot(mydata, aes(x = age, y = height, group = Occasion, color = Occasion)) + geom_point()

ggplot(mydata, aes(x = age, y = height, group = Subject, color = Subject)) + geom_line()

Wrapping occasions up in a panels (facets)

ggplot(mydata, aes(x = age, y = height)) + facet_wrap(~Subject) + geom_point() + geom_line()

ggplot(Oxboys, aes(x = height)) + facet_wrap(~Occasion) + geom_histogram()
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Please visit http://docs.ggplot2.org for more examples and the complete documentation of ggplot2.

Exercise 1: Plotting Verhulst dynamics

A solution of the Verhulst ODE \[ \dot x = rx\left( 1-\frac{x}{K} \right), \quad x(0)=x_0 \qquad (1) \] is given by \[ x(t) = \frac{Kx_0}{x_0 + (K-x_0)e^{-rt}} \qquad (2) \]

Exercise 2: Data simulation and error bars

Consider Eq. (2) on the interval \(t\in [0,1]\) given \(x_0 = 0.1, K = 0.5, r = 4\). A data point is to be simulated by adding a normally distributed random number \(r\) with mean 0 and standard deviation 0.05, \(r\sim\mathcal{N}(0,0.05^2)\) (see rnorm), to the function value \(x\).

Cathedral exercise

What distinguishes our cathedral from all other German Gothic cathedrals?