How to Center the Plot Title in R ggplot2

To center the plot title in R ggplot2, follow the below steps:

  1. Create a “ggplot” object.
  2. Use the “plot title” to explain the main findings.
  3. Use the “theme()” function and specify the argument “hjust = 0.5” in the “element_text()” function.

Example: R Program to  Center the Plot Title in ggplot2

# Load required packages

# Create a simple ggplot2 plot
plt <- ggplot(mtcars, aes(x = mpg, y = wt)) +
       geom_point() +
       labs(title = "Scatterplot of MPG vs. Weight") +
       theme(plot.title = element_text(hjust = 0.5))

# Print the plot


How to Center the Plot Title in R ggplot2

In this example, we created a scatterplot of the mtcars dataset, displaying miles per gallon (MPG) against weight (WT).

We set the plot title using the labs() function and then adjust the title’s horizontal justification (hjust) inside the theme() function. Setting hjust = 0.5 centers the title.

Here’s a breakdown of the code:

  1. Load the ggplot2 package with the library(ggplot2).
  2. Create a scatterplot with ggplot() and geom_point() functions using the mtcars dataset.
  3. Add a plot title with the labs() function.
  4. Adjust the plot title’s horizontal justification using the theme() function and setting the plot.title = element_text(hjust = 0.5).
  5. Print the plot with the print() function.

That’s it.

Leave a Comment