How to Center Plot Title/subtitle in ggplot2

Move title and subtitle to the center of ggplot
Move title and subtitle to the center of ggplot

In this tutorial, we will learn one of the most basic and useful tip to place the title (and subtitle) of a plot to center using ggplot2. When we add title to a plot made with ggplot2, it places the title left aligned to the plot by default. Sometimes you might want to place the title to center of the plotting area.

We will first make a plot with default title position using ggplot2 and then we will move the plot title to the center in ggplot2. And then we will also see how to move subtitle of the plot to center in ggplot2.

Load packages and data

Let us start with loading tidyverse and palmerpenguin package to make plot with a title using ggplot.

library(tidyverse)
library(palmerpenguins)
theme_set(theme_bw(16))

Let us make a denisty plot with a plot title at default location i.e. left of the plotting area.

penguins %>%
  drop_na() %>%
  ggplot(aes(x=body_mass_g, fill=sex))+
  geom_density(alpha=0.5)+
  labs(title="Body Mass Distribution")
Plot with default title location in ggplot2

Move title to the center of plot with element_text()

We can adjust the text element of a ggplot2 using element_text() theme element. To customize the title text, we will use plot.title as argument to theme() function. And we specify hjust=0.05 as argument to element_text() function as shown below.

penguins %>%
  drop_na() %>%
  ggplot(aes(x=body_mass_g, fill=sex))+
  geom_density(alpha=0.5)+
  # add title text
  labs(title="Body Mass Distribution")+
  # move the title text to the middle
  theme(plot.title=element_text(hjust=0.5))
Move title to the center of plot in ggplot2

Move subtitle to the center of plot with element_text()

Similarly, to move the subtitle to the middle of the plot, we need to use “plot.subtitle” to customize the text theme element with element_text().

penguins %>%
  drop_na() %>%
  ggplot(aes(x=body_mass_g, fill=sex))+
  geom_density(alpha=0.5)+
  labs(title="Body Mass Distribution",
       subtitle="Male and Female")+
  # move the title text and subtitle text to the middle
  theme(plot.title=element_text(hjust=0.5),
        plot.subtitle=element_text(hjust=0.5))
Move title and subtitle to the center of ggplot
Exit mobile version