To center the plot title in R ggplot2, follow the below steps:
- Create a “ggplot” object.
- Use the “plot title” to explain the main findings.
- 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 library(ggplot2) # 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 print(plt)
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:
- Load the ggplot2 package with the library(ggplot2).
- Create a scatterplot with ggplot() and geom_point() functions using the mtcars dataset.
- Add a plot title with the labs() function.
- Adjust the plot title’s horizontal justification using the theme() function and setting the plot.title = element_text(hjust = 0.5).
- Print the plot with the print() function.
Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Data Science and Machine Learning, and he is an expert in R Language.