How to Use Layers in ggplot2 in R - dummies

How to Use Layers in ggplot2 in R

By Andrie de Vries, Joris Meys

The basic concept of a ggplot2 graphic in R is that you combine different elements into layers. Each layer of a ggplot2 graphic contains information about the following:

  • The data that you want to plot: For ggplot(), this must be a data frame.

  • A mapping from the data to your plot: This usually is as simple as telling ggplot() what goes on the x-axis and what goes on the y-axis.

  • A geometric object, or geom in ggplot terminology: The geom defines the overall look of the layer (for example, whether the plot is made up of bars, points, or lines).

  • A statistical summary, called a stat in ggplot: This describes how you want the data to be summarized (for example, binning for histograms, or smoothing to draw regression lines).

That was a mouthful. In practice, you describe all this in a short line of code. For example, here is the ggplot2 code to plot the faithful data using two layers.The first layer is a geom that draws the points of a scatterplot; the second layer is a stat that draws a smooth line through the points.


> ggplot(faithful, aes(x=eruptions, y=waiting)) + geom_point() + stat_smooth()