Good practice for ordering `ggplot2` elements?

I was wondering if there is any consensus on "good practice" for the ordering ggplot2 elements. A complicated plot will at least have:

  • scales (x, y)
  • geoms (points, lines, bars, text)
  • theme
  • labels
  • facets

For most part as the user, I have total flexibility in the order I arrange these elements. What is best practice in ordering these for readability?

2 Likes

If you go back to the ggplot book, the grammar of graphics philosophy is heavily oriented toward layers. This naturally leads to an approach of beginning with the most basic and proceeding to the more specific.

library(ggplot2)
# adapted from documentation
# base object -- note not suitable for ALL geoms, such as geom_histogram()
p <- ggplot(mtcars, aes(wt, mpg))
# add a geom
p + geom_point()

# add a second geom
p + geom_point() + geom_line()

# add a theme
p + geom_point() + geom_line() + theme(
  panel.background = element_rect(fill = NA),
  panel.grid.major = element_line(colour = "grey50"),
  panel.ontop = TRUE) 

# add a title and lable axes 
p + geom_point() + geom_line() + theme(
  panel.background = element_rect(fill = NA),
  panel.grid.major = element_line(colour = "grey50"),
  panel.ontop = TRUE) + ggtitle("Illustrative Plot") + xlab("Miles per gallon") + ylab("Horsepower")

Created on 2020-01-06 by the reprex package (v0.3.0)

1 Like

I'm not sure if I know of a consensus/good practice, but I typically do:

  1. ggplot() call.
  2. All geom_ and/or stat_ functions (in the order that I want them to get some elements drawn over others, for example).
  3. scale_ functions
  4. facet_ functions
  5. Labels (using labs(), usually)
  6. theme() settings

In the (rare) event that I need more fine-grained control over my legends, I put the functions controlling them in between the facet specifications and the labels.

3 Likes

I do exactly the same thing so maybe there is a practical consensus.

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.