Plotting with the ggplot2 Package Answer Key

Author

Will Gammerdinger

Published

July 1, 2025

Exercise 1

  1. The current axis label text defaults to what we gave as input to geom_point (i.e the column headers). We can change this by adding additional layers called xlab() and ylab() for the x- and y-axis, respectively. Add these layers to the current plot such that the x-axis is labeled “Age (days)” and the y-axis is labeled “Mean expression”.
# Add axes labels to the plot
ggplot(new_metadata) +
  geom_point(aes(x = age_in_days, y= samplemeans, color = genotype,
            shape=celltype), size=2.25) +
  theme_bw() +
  theme(axis.title = element_text(size=rel(1.5))) +
  xlab("Age (days)") +
  ylab("Mean expression")

  1. Use the ggtitle layer to add a plot title of your choice.
# Add title to the plot
ggplot(new_metadata) +
  geom_point(aes(x = age_in_days, y= samplemeans, color = genotype,
            shape=celltype), size=2.25) +
  theme_bw() +
  theme(axis.title = element_text(size=rel(1.5))) +
  xlab("Age (days)") +
  ylab("Mean expression") +
  ggtitle("Mean Expression by Age")

  1. Add the following new layer to the code chunk theme(plot.title=element_text(hjust=0.5)).
# Center plot title
ggplot(new_metadata) +
  geom_point(aes(x = age_in_days, y= samplemeans, color = genotype,
            shape=celltype), size=2.25) +
  theme_bw() +
  theme(axis.title = element_text(size=rel(1.5))) +
  xlab("Age (days)") +
  ylab("Mean expression") +
  ggtitle("Mean Expression by Age") +
  theme(plot.title=element_text(hjust=0.5))

  • What does it change?

    It centers the title

  • How many theme() layers can be added to a ggplot code chunk, in your estimation?

    There is no limit to the number of theme() layers that can be added to a ggplot code chunk.