Grammar of Graphics with ggplot2 - Part 2

Ha Khanh Nguyen


  • In some cases, the plot is clearer and more informative to be split into facets, subplots that each display one subset of the data.

  • There are 2 main methods to use facets in ggplot2:
    • facet_wrap()
    • facet_grid()


  • Use facet_wrap() to facet your plot by a single variable.
  • The first argument of facet_wrap: ~ followed by a variable name.
  • The variable that you pass should be discrete (categorical).


  • Use facet_grid() to facet your plot on the combination of two variables.
  • The first argument is two variable names separated by a ~.
  • Both of the variables should be discrete (categorical).

  • You can also replace one of the variable names with . to get a similar result as facet_wrap().


  • Question: What happens if you facet on a continuous variable?

Geometric Objects

  • A geom is the geometrical object that a plot uses to represent data.

  • Both plots describe the same relationship, yet they use different geoms to plot.
  • Use geom_...() function to specify the geom you want to use.

geom_...() function

  • Every geom function in ggplot2 takes a mapping argument.
  • But not every aesthetic works with every geom.

  • Example:
    • shape is an aesthetic that does not work with geom_smooth()
    • But geom_smooth() will draw a different line, with a different linetype, for each unique value of the variable that you map to linetype.

ggplot2 cheatsheet

  • ggplot2 provides over 40 geoms!
  • The best way to get a comprehensive view of the ggplot2 package is to take a look at the ggplot2 cheatsheet.
    • The cheatsheet link is also available on the course website.