Conclusion

Congratulations, you’ve worked through the full grammar of graphics: data, aesthetic mappings, geometries, labels, themes, faceting, and composing multiple plots into one figure.

Self-Test Assignment

The exercises so far have all used the mpg dataset. To check whether you can transfer what you’ve learned to data you haven’t seen before, work through the following tasks using the diamonds dataset: another dataset built into ggplot2, containing the price and physical characteristics of about 54,000 diamonds. Load it the same way you loaded mpg: it becomes available as soon as you library(ggplot2). Run ?diamonds in your own R session first to see what each variable measures.

  1. Inspect the data. Use glimpse() or str() on diamonds and identify at least one categorical variable and one continuous variable you haven’t used in the tutorials.
  2. One categorical variable. Create a bar chart showing how many diamonds fall into each level of cut.
  3. One continuous variable. Create a histogram of price. Try at least two different binwidth values and note how your impression of the distribution changes.
  4. Two continuous variables. Create a scatterplot of carat (x-axis) against price (y-axis). Add a fitted trend line. Does a linear (method = "lm") or a smoothed (method = "loess") trend look like a better summary of the relationship, and why?
  5. Continuous by categorical. Create a boxplot (or violin plot) of price broken down by cut. What do you notice about how price relates to cut quality — is the relationship what you expected?
  6. Facet and polish. Take your scatterplot from Task 4, colour the points by clarity, and facet the plot by cut. Add clear axis labels, a title, and a theme of your choice.
  7. Compose. Arrange your bar chart (Task 2), histogram (Task 3), and faceted scatterplot (Task 6) into a single figure using grid.arrange() (or ggpubr::ggarrange()).
  8. Write it up. In two or three sentences, summarise the main relationship(s) you found between diamond characteristics and price, referring to the specific plots you made as evidence.

Work through these in your own R environment.

Next Steps

If you’d like to continue building on these skills, the R for Data Science book (free online) has a much deeper treatment of both the grammar of graphics and exploratory data analysis more broadly.

Back to top