Rotating and spacing axis labels in ggplot2 can be easily accomplished using the theme() and element_text() functions.
The theme() function customizes the non-data components of a plot, such as titles, labels, fonts, backgrounds, gridlines, and legends.
Follow the below steps to rotate and space axis labels in ggplot2.
Step 1: Install and load the ggplot2 package (if you haven’t already)
install.packages("ggplot2")
library(ggplot2)
Step 2: Create a simple ggplot2 plot using sample data
library(ggplot2)
data <- data.frame(
Category = c(
"Category A", "Category B", "Category C",
"Category D", "Category E"
),
Values = c(10, 25, 35, 45, 15)
)
plot <- ggplot(data, aes(x = Category, y = Values)) +
geom_bar(stat = "identity")
Step 3: Rotate and space axis labels using the theme() and element_text() functions
plot <- ggplot(data, aes(x = Category, y = Values)) +
geom_bar(stat = "identity") +
theme(axis.text.x = element_text(
angle = 45, hjust = 1, vjust = 1,
size = 12, margin = margin(t = 5, b = 5)
))
In this example, we used the element_text() function to apply a 45-degree rotation to the x-axis labels, horizontally and vertically adjusted them with hjust and vjust parameters (set to 1), set the font size to 12, and added a margin around the labels.
Step 4: Print the plot using the print() function
You can print the plot using the print() function. You can customize the angle, size, and margin values according to your preferences. Check out the complete code.
library(ggplot2)
data <- data.frame(
Category = c(
"Category A", "Category B", "Category C",
"Category D", "Category E"
),
Values = c(10, 25, 35, 45, 15)
)
plot <- ggplot(data, aes(x = Category, y = Values)) +
geom_bar(stat = "identity") +
theme(axis.text.x = element_text(
angle = 45, hjust = 1, vjust = 1,
size = 12, margin = margin(t = 5, b = 5)
))
Output
You can see that it’s a bar chart with five categories on the x-axis (Category A to E) and their corresponding values on the y-axis.
The x-axis labels will be rotated 45 degrees, with custom spacing and font size.
That’s it.

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.