STAT 545 - Fall 2025
ggplot2create effective data visualizations
explore the grammar of ggplot2
Quick links:
Install (if necessary) and load in the following packages:
We want to investigate if there is a relationship between the number of cylinders (cyl), fuel efficiency (mpg), and horsepower (hp) in the mtcars data set.
We can clearly see that cars with higher horsepower tend to be less fuel efficient (have lower miles per gallon).
Cars with higher horsepower also tend to have a higher number of cylinders.
That was a lot easier to deduce than when we were reading numbers off of a large table. We will show how to build this exact plot in this lecture!
Data visualizations are often preferred to aid with identify patterns and relationships and emphasizing important findings in a research projects
So, what’s the best visualization?
Once you know what you want to show, we need to convey the message as clearly and simply as possible
Make it clear as a “standalone”
Minimize noise
Don’t use colours randomly - it may cause us to see false patterns
Don’t overlap plots
Use as few plots as possible, but don’t be afraid to separate data to plot if it makes things clearer
Consider the accessibility of your chart
up to 10% of the population has colourblindness
make it low-vision friendly and provide descriptions where possible
ggplot2 and the Grammar of Graphicsggplot2 is based on the grammar of graphics, which is a systematic approach for describing different components or aspects of a graph. It involves seven components (required components are indicated with the *):
Data*
Aesthetic mappings*
Geometric objects*
* = required component
ggplot2 and the Grammar of GraphicsScales
Statistical transformations
Coordinate system
Facet
It’s okay if you don’t quite understand all of these components yet. We will walk through examples of commonly used plots and discuss which components are necessary!
mtcarsLet’s say you’d like to see if there is a relationship between miles per gallon and horsepower of cars in the mtcars data set. As both of these variables are numeric, we could build a scatterplot as we are comparing two quantitative/numeric variables.
mtcarsLet’s say you’d like to see if there is a relationship between miles per gallon and horsepower of cars in the mtcars data set. As both of these variables are numeric, we could build a scatterplot (more on this next class).
The ggplot() function takes two arguments:
data (the data frame or tibble containing your data that you’d like to plot)
mapping (aesthetic mappings applied to the entire plot. We use the aes() function inside of this argument.).
mtcarsLet’s start building the scatterplot! Let’s plot mpg (miles per gallon) on the x axis and hp on the y axis by piping the dataset into the ggplot function:
Notice that we haven’t actually plotted anything! ggplot doesn’t know what type of plot we want to draw, only that we want mpg on the x axis and hp on the y axis from the mtcars data we provided.
mtcarsTo tell ggplot that we want a scatterplot, we are going to add a layer to the plot using the + at the end of the previous line. geom_point() is the geometric object we’d like to add (i.e., a scatterplot):
We now have created a scatterplot! It’s fine, but we can elevate this.
mtcarsLet’s colour the points by the number of cylinders!
Note: because cyl is written as a number, R is probably going to read it as a numeric value. However, we only have three possible categories for the number of cylinders, so we first should tell R to treat this as a categorical variable!
mtcarsWe can treat cyl as a categorical variable with mutate, where we overwrite the cyl variable as a factor. Then, we use color = cyl in the aes() function to tell ggplot to colour by this category!
Cool! But… this isn’t super colourblind-friendly.
mtcarsLet’s turn to the RColorBrewer package to select a friendlier colour scheme. The colour palette “Set2” is more colourblind-friendly:
mtcarsTo be even more accessible, let’s change the shape of the points by cylinder type by adding shape = cyl to the aes()!
mtcarsNow, let’s add better labels to our X and Y axes:
mtcarsWe can also change the title of our legend. We’ll have to specify the title twice as we’ve grouped by colour and shape:
mtcarsThe grey background is still a bit distracting, so we could remove it by giving out ggplot a more minimal theme:
mtcarsAnd finally, let’s add a descriptive title!
Now, this is a nice visualization! We can clearly see that cars with higher horsepower tend to be less fuel efficient (have lower miles per gallon). Cars with higher horsepower also tend to have a higher number of cylinders.
mtcarsTip
The \n in the title is a special character that allows the line to break and fit on this size of plot.
Names of axes should have quotations “” around them.
The order of the layers doesn’t matter after the geom_layer() layer.
ggplotGoogle is absolutely your friend when building ggplots.
I don’t think I’ve ever made a plot without googling how to do it. ggplot is extremely powerful, flexible, and a bit scary to learn!
If you need to build a plot, search it! Need to plot two histograms, separated by groups (say, gender), side by side? I’d google: “ggplot histogram grouped by variable”. This brings me to this blog post by R Charts that has a TON of different side by side histograms with code! ggplot is very much a “learn by doing” skill.
Ask a question, then answer it
The purpose of a visualization is to answer a question about a dataset of interest.
A good visualization answers the question clearly. A great visualization also hints at the question itself.
Visualizations alone help us answer two types of questions:
(we need more tools + visualizations to answer the others)
A variable refers to a characteristic of interest and can be:
The types of variables (along with the question we wish to answer/explore) we have may depict the type of data visualization we should use.
Scatterplots are used to visualize the relationship between two quantitative variables
The scatterplot we made last class helped us determine that there was a relationship between these three variables!
Line plots are used to visualize trends with respect to an independent quantity
Barplots are used to visualize the comparison of amounts
Histograms are used to visualize the distribution of a single quantitative variable
This list is not exhaustive, but the following are banned from this class:
anything “3D”
pie charts
To Print to PDF (with your code!), do the following:
Open the in-browser print dialog CMD/CTRL + P or Right click > Print
Change the Destination setting to Save as PDF.
Change the Layout to Landscape.
Change the Margins to None. Enable the Background graphics option.
Click Save 🎉
In all cases, ensure the code chunks don’t get cut off (i.e., a line is too long). You will not be able to edit these from the PDF directly (though you could open the slides again and copy-and-paste to re-run the code!)