How to wrap long strip labels in facet_wrap

In this tutorial, we will learn how wrap long strip labels while using facet_wrap(). When the labels of a specific facet is long it will go beyond the boundaries of the strip in a facet and will not be legible. In this post, we will learn how to use a labeller function in ggplot2 to wrap the long strip labels by specifying the width we need.

How to wrap long titles in a facet plot
How to wrap long titles in a facet plot

Let us load tidyverse.

library(tidyverse)
theme_set(theme_bw(16))

Let us create small dataframe to use for making a boxplot with facets. One the groups in the facet has a long group name.

df <- data.frame(measurement = rnorm(20,mean=30), 
                 group = c(rep('A really long group variable name that needs to be wrapped',10),
                           rep('group1',10)), 
                 sex = c(rep(c('M','F'),10)))

df %>% head()

   measurement                                                      group sex
1     29.78323 A really long group variable name that needs to be wrapped   M
2     29.80423 A really long group variable name that needs to be wrapped   F
3     31.88631 A really long group variable name that needs to be wrapped   M
4     30.95879 A really long group variable name that needs to be wrapped   F
5     29.69200 A really long group variable name that needs to be wrapped   M
6     29.45745 A really long group variable name that needs to be wrapped   F

Let us make a boxplot using facet_wrap() function in ggplot2. In this plot we can see that one of the strip label is very long and goes over the strip box in the facet. And that makes the label unreadable.

df %>%
  ggplot(aes(sex, measurement, color = sex)) +
  geom_boxplot() +
  facet_wrap(~group) +
  theme(legend.position = "none")
ggsave("facet_wrap_example_with_long_strip_label.png")
How to wrap a facet plot dynamically with long strip label

How to wrap a facet plot dynamically with long strip label

ggplot2 has useful labeller functions for formatting the strip labels of facet grids and wraps. To wrap long strip label into multiline label within the facet, we can use the labeller – label_wrap_gen() function that specifies the width of the label.

df %>%
  ggplot(aes(sex, measurement, color = sex)) +
  geom_boxplot() +
  facet_wrap(~group, labeller = label_wrap_gen(24))+
  theme(legen.position="none")
ggsave("wrapping_the_long_strip_label_with_labeller_in_facet_wrap.png")

With the use of the labeller, we have the label wrapped dynamically within the facet as we wanted.

Wrap a long strip label in a facet plot with labeller

Exit mobile version