Automatically Wrap Long Axis Labels of ggplot2 Plot in R (Example Code)

In this tutorial, I’ll illustrate how to automatically wrap long axis labels of a ggplot2 graphic in the R programming language.

Preparing the Example

data(iris)                     # Some example data
levels(iris$Species) <- c("setosa label",
                          "The very long versicolor label",
                          "The extremly long virginica plot label that cannot be shown in one line")
head(iris)
#   Sepal.Length Sepal.Width Petal.Length Petal.Width      Species
# 1          5.1         3.5          1.4         0.2 setosa label
# 2          4.9         3.0          1.4         0.2 setosa label
# 3          4.7         3.2          1.3         0.2 setosa label
# 4          4.6         3.1          1.5         0.2 setosa label
# 5          5.0         3.6          1.4         0.2 setosa label
# 6          5.4         3.9          1.7         0.4 setosa label
install.packages("ggplot2")    # Install & load ggplot2
library("ggplot2")
my_plot <- ggplot(iris,        # Draw ggplot2 plot with default labels
                  aes(x = Species,
                      y = Sepal.Width)) +
  geom_bar(stat = "identity")
my_plot

r graph figure 1 automatically wrap long axis labels ggplot2 r

Example: Specify Maximum Width of Labels in ggplot2 Graphic Using str_wrap() Function

install.packages("stringr")    # Install stringr package
library("stringr")             # Load stringr
my_plot +                      # Set maximum length for each line
  scale_x_discrete(labels = function(x) str_wrap(x, width = 15))

r graph figure 2 automatically wrap long axis labels ggplot2 r

Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top