How to Easily Add and Modify Titles in ggplot2

Working with titles in ggplot2

This tutorial explains how to add and modify plot titles in ggplot2.

Adding a Title in ggplot2

By default, ggplot2 does not include a title in plots.

For example, the following code shows how to create a basic scatterplot in ggplot2. Notice that the plot has no title:

#load ggplot2
library(ggplot2)

#create some data to work with
data <- data.frame(x = 1:10, y = 1:10)

#create scatterplot with ggplot2
ggplot(data, aes(x, y)) +
  geom_point()

ggplot2 scatterplot with no title

In order to add a title, we can use the ggtitle() argument:

ggplot(data, aes(x, y)) +
  geom_point() +
  ggtitle("This is a chart title")

ggplot2 scatterplot with a basic title

Aligning a Title in ggplot2

By default, the title in ggplot2 is left-aligned.

We can modify the title to be center-aligned using the following code:

ggplot(data, aes(x, y)) +
  geom_point() +
  ggtitle("This is a chart title") +
  theme(plot.title = element_text(hjust = 0.5))

ggplot2 scatterplot with title center-alignedOr we can modify the title to be right-aligned using the following code:

ggplot(data, aes(x, y)) +
  geom_point() +
  ggtitle("This is a chart title") +
  theme(plot.title = element_text(hjust = 1))

ggplot2 scatterplot with a right-aligned title

Splitting a Title into Multiple Lines in ggplot2

If our title is quite long, we can split it into multiple lines usingĀ \n

ggplot(data, aes(x, y)) +
  geom_point() +
  ggtitle("This chart title is long so\nwe will split it into two lines.")

ggplot2 title split into two lines

Modifying Title Appearance in ggplot2

We can also modify the color, size, height, font style, and font family of titles in ggplot2 using the element_text() function.

Related: Full RDocumentation on element_text function

The following chunks of code show various examples of modifying the title appearance in ggplot2:

ggplot(data, aes(x, y)) +
  geom_point() +
  ggtitle("This is a chart title") +
  theme(plot.title = element_text(color="red", size=20, face="bold"))

Chart title in ggplot2 with custom style

ggplot(data, aes(x, y)) +
  geom_point() +
  ggtitle("This is a chart title") +
  theme(plot.title = element_text(color="blue", family = "serif", face="italic"))

Modifying a chart title in ggplot2

ggplot(data, aes(x, y)) +
  geom_point() +
  ggtitle("This is a chart title") +
  theme(plot.title = element_text(color="green", hjust = 0.5, face = "bold.italic"))

Center-aligned italic ggplot2 title

Leave a Reply

Your email address will not be published. Required fields are marked *