Chapter 12 Pimping your plots
In this chapter you will learn, by following examples, how to customise plots made with ggplot to improve readability or for aesthetic reasons.
We will cover the following:
- Modifying axes (log transform, different tick marks/ranges etc.).
- Colour schemes.
- Themes - built-in sets of styles.
- Multiple sub-plots in a plot.
- Saving your plots.
In this chapter we use these packages:
For these examples I will use the animal life-history data set Anage.9
You can remind yourself what this data looks like using commands like summary, str and names.
I will process the data a bit to make it easier to work with. One of the commands might be new to you - rename. This is simply a way of renaming columns, in this case to make them more user-friendly (e.g. I want to rename the column “Metabolic.rate..W.” to “BMR” for basal metabolic rate).
I will also use mutate to (1) convert the mass from grams to kilograms and (2) create a new variable called “BMRperKg” which standardises metabolic rate by expressing it as rate per kilogram.
anage <- x %>%
mutate(Species = paste(Genus, Species)) %>%
rename(
Longevity = "Maximum.longevity..yrs.",
Mass = "Body.mass..g.",
BMR = "Metabolic.rate..W."
) %>%
select(Class, Order, Species, Mass, Longevity, BMR) %>%
filter(Class %in% c(
"Aves", "Amphibia",
"Mammalia", "Reptilia"
)) %>%
mutate(
Mass = Mass / 1000,
BMRperKg = BMR / Mass
)
summary(anage)## Class Order Species Mass
## Length :3231 Length :3231 Length :3231 Min. : 0.0008
## N.unique : 4 N.unique : 65 N.unique :3231 1st Qu.: 0.0259
## N.blank : 0 N.blank : 0 N.blank : 0 Median : 0.1313
## Min.nchar: 4 Min.nchar: 5 Min.nchar: 9 Mean : 13.1879
## Max.nchar: 8 Max.nchar: 19 Max.nchar: 31 3rd Qu.: 1.1112
## Max. :3672.0000
## NAs :2604
## Longevity BMR BMRperKg
## Min. : 0.40 Min. : 0.0001 Min. : 0.04543
## 1st Qu.: 10.20 1st Qu.: 0.2655 1st Qu.: 2.21913
## Median : 16.20 Median : 0.7050 Median : 4.57453
## Mean : 19.37 Mean : 11.8309 Mean : 7.04391
## 3rd Qu.: 24.45 3rd Qu.: 3.1370 3rd Qu.: 9.86860
## Max. :211.00 Max. :2336.5000 Max. :45.76923
## NAs :432 NAs :2604 NAs :2604
12.1 A basic plot
Now let’s start with a basic plot. You will see a warning about removing rows with missing values. This is just a warning to let you know that there are missing (NA) values in the data you are plotting.
(p1 <- ggplot(anage, aes(x = Mass, y = BMR, colour = Class)) +
geom_point(alpha = 0.3)) # use alpha for transparent points
12.2 Axis limits
These points are really spread out. One option is to set the range over which the axes are allowed to go using xlim and ylim. Be careful: xlim and ylim do not just zoom in, they remove every point outside the limits (that is what the “Removed rows” warning means). If you only want to zoom, use coord_cartesian(xlim = c(0, 500), ylim = c(0, 300)), which keeps all the data.

12.3 Transforming the axis (log scale)
In this particular case, a log scale is best because even after focusing on a smaller part of the range of values you can see that the points are still concentrated at smaller values. In a moment you will also see that log-transforming the data makes the cloud of points pleasingly linear.
You can set a log scale by using the commands scale_x_continuous(transform = "log") and scale_y_continuous(transform = "log"). (In older versions of ggplot2 this argument was called trans; you may see that in examples online. scale_x_log10() and scale_y_log10() are shortcuts that do the same with base-10 logs.)

Now the axis labels are not ideal. Let’s change them.
12.4 Changing the axis tick marks
This looks nice, but the numbers on the axis are not very nice. Using summary(anage$BMR) tells us that the range of data is from 0.0001 to 2336.5. We could place tick marks anywhere on this axis, but let’s try 0.0001, 0.001, 0.01, 0.1, 1, 10, 100, 1000.
(p2 <- p1 +
scale_x_continuous(transform = "log") +
scale_y_continuous(
transform = "log",
breaks = c(0.0001, 0.001, 0.01, 0.1, 1, 10, 100, 1000)
))
Using summary(anage$Mass) tells us that the range of data is from 0.001 to 3672. We could place tick marks anywhere on this axis, but let’s try 0.001, 0.01, 0.1, 1, 10, 100, 1000.
(p2 <- p1 +
scale_x_continuous(
transform = "log",
breaks = c(0.001, 0.01, 0.1, 1, 10, 100, 1000)
) +
scale_y_continuous(
transform = "log",
breaks = c(0.0001, 0.001, 0.01, 0.1, 1, 10, 100, 1000)
)
)
If you don’t like the scientific notation (e.g. 1e+03 instead of 1000), you can give your own tick labels with the labels argument. The labels are matched to the breaks in order, so give one label per break.
p2 <- p1 +
scale_x_continuous(
transform = "log",
breaks = c(0.001, 0.01, 0.1, 1, 10, 100, 1000),
labels = c("0.001", "0.01", "0.1", "1", "10", "100", "1000")
) +
scale_y_continuous(
transform = "log",
breaks = c(0.0001, 0.001, 0.01, 0.1, 1, 10, 100, 1000),
labels = c("0.0001", "0.001", "0.01", "0.1", "1", "10", "100", "1000")
)
p2
Check your tick labels after you change them. A common trap is rounding: with labels = scales::label_number(accuracy = 1) every value below 0.5 is shown as “0”.
12.5 Axis labels
Now, let’s think about the axis labels. The labels in the plots so far have no units indicated, and might not be easy to interpret for the reader. Let’s add units, and also spell out more fully what “BMR” and “Mass” means (the axes is basal metabolic rate in Watts and adult body mass in kg).

12.6 Points hiding other points
Look closely: there are 171 birds in these data, but you can hardly see them. ggplot draws points in the order of the rows, and here the 422 mammals come after the birds, so they are drawn on top. One fix is to sort the data so that the largest group is drawn first. add_count() adds a column n with the number of rows in each class, and arrange(desc(n)) puts the biggest class first.

Adding a data frame to an existing plot with + replaces its data. (In versions of ggplot2 older than 4.0 you had to use %+% instead of + for this; you may see that in examples online.) You could also simply rebuild the plot with ggplot(anage_sorted, ...). Transparency (alpha) also helps when points overlap.
12.7 Colours
What about those colours? The ggplot package uses some default colours that are OK, but sometimes you will want to make a change.
You can “manually” adjust colours using the scale_colour_manual function. You can either name individual colours (e.g. “red”,“green”,“orange”,“black”)10, or you can find their so-called “hex-codes” from a site like http://colorbrewer2.org/ or https://htmlcolorcodes.com/color-picker/. You can add two more hexadecimal digits after the hex code to set the opacity of the colour, from 00 (fully transparent) to FF (fully opaque). These are hexadecimal, not percentages: “#FF0000BF” is red at about 75% opacity, and “#FF000075” is red at about 46% (hexadecimal 75 is 117 out of 255).
With colour names…

And with some hex codes…

Another alternative is to use some of ggplot’s built in “palettes” of colour combinations. For example, there are several palettes called “viridis”.

Try using other option arguments A,
B, C and E. Try also adding an
argument for transparency alpha = 0.5.
Here’s a couple more palettes. There’s one for shades of grey…

There’s another set of palettes called “colour brewer”. These come in three types. Qualitative palettes (such as “Dark2”, “Set2” and “Paired”) use clearly different colours with no order, which is what we need for unordered categories such as Class. Sequential palettes (such as “Blues”) run from light to dark and suit ordered values. Diverging palettes (such as “RdYlBu” and “BrBG”) run between two colours through a neutral middle, and suit data with a meaningful midpoint (e.g. change from zero). Try “Set2” and “Paired”, and see ?scale_colour_brewer for more options.

12.8 Themes
Finally, ggplot includes the option to set a theme for the plots. Themes make adjustments to the “look” of the plot. It is possible to write your own themes, but I recommend using some ready-made ones. You can implement them by adding them as you would any other addition to the ggplot command (e.g. + theme_light()).
There are several themes included with ggplot. Try my favourite, theme_minimal(). Then try theme_classic() and theme_dark().
For more theme fun, you can install packages that include more themes. The best one is called ggthemes (remember that you only need to install the package once). Try theme_economist(), theme_tufte() and (ugh!) theme_excel(). You can see what other themes there are in this package at https://jrnold.github.io/ggthemes/reference/index.html (some of them are really ugly in my opinion!).

This package also includes some useful colour scales, including scale_color_colorblind(), which uses the Okabe-Ito colours.11 These stay distinguishable for people with the commonest kinds of colour-vision deficiency (about 1 in 12 men and 1 in 200 women have red-green colour-vision deficiency). The viridis palettes above are also designed with this in mind. You can check any figure with a free simulator such as Coblis.

12.9 Moving the legend
By default, the legend is placed on the right. You can move it around by adding a theme argument to your plot commands. It can also be placed on the “top”, “bottom”, or “left”. You can also remove the legend altogether by using legend.position = "none". You might also want to remove the legend title using the theme argument legend.title = element_blank().

12.10 Combining multiple plots
It is often useful to combine two or more plots into a single figure. For example, many journals have strict limits on the number of plots so it is useful to combine plots into “Figure 1A and B” etc.
There are several R packages that can do this and my favourite is called patchwork.
I will illustrate it by first making another plot, this time showing the relationship between body mass and standardised BMR (BMR per kg). Because I am combining the plots into a smaller space I have decided to remove the figure legend (I could put it in the figure caption instead).
# PlotA (this is what you have already created above)
plotA <- ggplot(anage, aes(x = Mass, y = BMR, colour = Class)) +
geom_point(alpha = 0.5) +
scale_x_continuous(
transform = "log",
breaks = c(0.001, 0.01, 0.1, 1, 10, 100, 1000)
) +
scale_y_continuous(
transform = "log",
breaks = c(0.0001, 0.001, 0.01, 0.1, 1, 10, 100, 1000)
) +
xlab("Adult body mass (kg)") +
ylab("Basal metabolic rate (W)") +
theme_minimal() +
theme(
legend.position = "bottom",
legend.title = element_blank()
)
(plotB <- ggplot(anage, aes(
x = Mass, y = BMRperKg,
colour = Class
)) +
geom_point(alpha = 0.5) +
scale_x_continuous(
transform = "log",
breaks = c(0.001, 0.01, 0.1, 1, 10, 100, 1000)
) +
scale_y_continuous(
transform = "log",
breaks = c(0.1, 1, 10)
) +
xlab("Adult body mass (kg)") +
ylab("Mass-specific BMR (W/kg)") +
theme_minimal() +
theme(legend.position = "none")
) # This one is wrapped in brackets so that R shows it
Now I can combine these using the very simple syntax like this:

Journals usually want panels labelled A, B and so on. plot_annotation(tag_levels = "A") adds these tags for you.

You could place the sub-plots on top of each other like this.

If both panels need the same legend, show it once rather than twice. plot_layout(guides = "collect") gathers identical legends into one. Adding a theme with & (instead of +) applies it to every panel, so here it puts the legend at the bottom for both plots (overriding the legend.position = "none" we set for plotB), and patchwork then merges the two legends into one:
plotA + plotB +
plot_layout(guides = "collect") +
plot_annotation(tag_levels = "A") &
theme(legend.position = "bottom", legend.title = element_blank())
12.11 Saving your plot
You should, I think, already know about using the “Export” button in RStudio to save out your plot. This is useful and easy, but you should know that you can also save the plots using a typed command (ggsave) in your script. This command is handy because it allows you to automatically set the size, and file name of your plot.
The default setting for ggsave is that it will save the last plot that was printed to your computer screen to a file name that you specify. Therefore easiest way to use the command is to simply place the ggsave command immediately after your ggplot command. You should set the width and height of the plot and the units (the default is inches). It usually takes a few attempts and a bit of trial-and-error to choose the dimensions so that the plot looks nice.
The command can save to various file types including png, jpeg, pdf (see the ggsave help file for more). R knows what file type is chosen by checking the file extension in the file name (e.g. .png). I advise using png, with dpi = 300 for anything that will be printed.
Choose the size for where the figure will end up, not for how it looks on your screen. A figure made large and then shrunk into a report or a journal column gets tiny, unreadable text. Many journals use a single column about 8 cm wide and a full page width about 17 cm (check the author guidelines). Save at that size and look at the file before you use it:
At 8 cm you may need to tidy things up: fewer tick labels, a legend in two rows (guides(colour = guide_legend(nrow = 2))) or a shorter axis label.
12.12 Final word on plots
We have covered a lot of ground here. There is a lot to learn, but don’t feel like you have to remember all of these commands (I don’t). Mostly it is simply a case of remembering that it is possible to do these things, and knowing where to look up the commands. Obvious starting points are this course book, and the text book (including the online version!). You can also usually find help by Googling “ggplot” followed by what you are trying to do (e.g. “ggplot change axis ticks”). One web site I use often is Datanovia, which has an extensive set of ggplot2 tutorials (https://www.datanovia.com/learn/data-visualization/ggplot2/).
Even though we have covered a lot of ground we have still only gotten a taster of what ggplot is capable of. I encourage you to learn more. A useful resource for learning is the online “R graph gallery” at https://www.r-graph-gallery.com/, which shows you how to make and modify many types of plot.
AnAge, the database of animal ageing and longevity (https://genomics.senescence.info/species/). Tacutu, R. et al. (2018). Human Ageing Genomic Resources: new and updated databases. Nucleic Acids Research 46(D1): D1083–D1090. https://doi.org/10.1093/nar/gkx1042↩︎
Okabe, M. & Ito, K. (2008). Color Universal Design (CUD): how to make figures and presentations that are friendly to colorblind people. https://jfly.uni-koeln.de/color/↩︎