Why ggplot?

The core idea behind ggplot2 is that instead of learning a new function for every kind of plot, you learn one small “grammar” and reuse it everywhere.

Base R plotting: one function per plot type

Base R already lets you make plots. Here are three completely unrelated functions, each producing a different kind of plot from the mpg dataset.

Do: run the code below.

See: you get a histogram of engine displacement.

Now run this one.

See: a bar chart of cylinder counts.

Predict: before running the next cell, what do you think plot(x = mpg$displ, y = mpg$hwy) will produce?

Note

Think about it, then run the code to check.

Explain: hist(), barplot(), and plot() all produced a graphic, but each one has its own argument names, its own defaults, and its own quirks. If you wanted to add a colour legend or split the plot by another variable, you’d have to look up how to do it separately for each function.

Check your understanding

In your own words, what is the main disadvantage of base R’s approach to plotting, illustrated by the three functions above?

Each plotting function (hist(), barplot(), plot(), and many others) has its own syntax, its own set of arguments, and its own conventions for things like colour, legends, and axis labels. Knowledge doesn’t transfer well from one plot type to the next, so you effectively have to relearn plotting for every new geometry.

The grammar of graphics

When using ggplot2, every plot is built from the same set of layers:

  • Pass the data to ggplot().
  • Choose aesthetic mappings with aes(): here you determine which variable goes on the x-axis, the y-axis, colour, etc.
  • Choose a geometry with a geom_*() function: here you determine how the mapped data is drawn (points, bars, lines, …).
  • Optionally add labels, themes, coordinate systems, and facets.

Schematically:

ggplot(data = <DATA>) +
  <GEOM_FUNCTION>(mapping = aes(<MAPPINGS>))

Do: run this first ggplot2 plot.

See: a scatterplot of engine displacement (displ) against highway fuel economy (hwy). This is the same relationship you saw in the base R plot() call above, but built through the grammar-of-graphics recipe instead.

Predict: what do you think happens if you run the code below, with geom_point() deleted?

ggplot(data = mpg)

Test your prediction:

Explain: ggplot() on its own only sets up a blank coordinate system linked to your data, it doesn’t know what to draw yet. Nothing appears on the canvas until you add a geometry layer, because a plot needs both a mapping (which variables go where) and a geometry (how to draw them) before R can draw anything.

Back to top