Annotating ggplot in R


This entry is part 3 of 3 in the series R ggplot

How do you customize the look and feel of our ggplot plots in R? To annotate means to add notes to a document or diagram to explain or comment upon it. In ggplot 2 adding annotations to your plot can help explain the plot’s purpose or highlight important data. Labels and annotations will point their attention to key things and help them quickly understand your plot.

We can add titles, subtitles and captions. We use the label function for this. We use the plus (+) sign to add layers to our plots.

library('ggplot2')
library('palmerpenguins')
ggplot(data=penguins) +
  geom_point(mapping=aes(x=flipper_length_mm,y=body_mass_g,color=species)) +
  labs(title="Palmer Penguins: Body Mass and Flipper Length", subtitle="Sample of Three Penguin Species")

Captions are displayed in the bottom right corner of the plot. We can use captions to site the source of the data, for example. Here’ how we do that.

library('ggplot2')
library('palmerpenguins')
ggplot(data=penguins) +
  geom_point(mapping=aes(x=flipper_length_mm,y=body_mass_g,color=species)) +
  labs(title="Palmer Penguins: Body Mass and Flipper Length", subtitle="Sample of Three Penguin Species",
       caption="Data collected by Dr. Kristen Gorman")

Annotate Inside the Grid

You can add text right inside the grid. annotate(): useful for adding small text annotations at a particular location on the plot.

library('ggplot2')
library('palmerpenguins')
ggplot(data=penguins) +
  geom_point(mapping=aes(x=flipper_length_mm,y=body_mass_g,color=species)) +
  labs(title="Palmer Penguins: Body Mass and Flipper Length", subtitle="Sample of Three Penguin Species",
       caption="Data collected by Dr. Kristen Gorman") +
  annotate("text", x=220, y=3500, label="The Gentoos are the biggest", color="blue", fontface="bold", size=3)

Inside the Plot tab in the lower right corner of RStudio, you will find a button called Export. I saved the one below as an image. I choose PNG.

Click Me

Series Navigation<< Introduction to ggplot in RFacets in ggplot in R >>

Leave a Reply