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.
- Inspect the data. Use
glimpse()orstr()ondiamondsand identify at least one categorical variable and one continuous variable you haven’t used in the tutorials. - One categorical variable. Create a bar chart showing how many diamonds fall into each level of
cut. - One continuous variable. Create a histogram of
price. Try at least two differentbinwidthvalues and note how your impression of the distribution changes. - Two continuous variables. Create a scatterplot of
carat(x-axis) againstprice(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? - Continuous by categorical. Create a boxplot (or violin plot) of
pricebroken down bycut. What do you notice about how price relates to cut quality — is the relationship what you expected? - Facet and polish. Take your scatterplot from Task 4, colour the points by
clarity, and facet the plot bycut. Add clear axis labels, a title, and a theme of your choice. - Compose. Arrange your bar chart (Task 2), histogram (Task 3), and faceted scatterplot (Task 6) into a single figure using
grid.arrange()(orggpubr::ggarrange()). - 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.