2

I want to summarize several columns using facet_wrap. I want to give several of the facet panes long titles. For example:

set.seed(123)

df <- 
  data.frame(
    a = sample(0:1, 20, replace = T),
    b = sample(1:4, 20, replace = T)
  )

names <- list(
  "a" = "Nice table 1",
  "b" = "Here is a really long title that I would like to wrap within the facet pane")

labeller_fun <- 
  function(variable,value){
  return(names[value])
  }

ggplot(gather(df,, factor_key = TRUE), aes(x = factor(value))) + 
geom_bar() + 
facet_wrap(~ key, scales = "free_x", as.table = TRUE, labeller = labeller_fun) + 
xlab("")

Here, the long title spills over and is mostly invisible. Is there a way to wrap the long text automatically in the pane title box?

lethalSinger
  • 606
  • 3
  • 9

1 Answers1

3

You can use the function str_wrap from stringr packages and add it to the return values of your "labeller_fun" function.

With the parameter width, you can specify the maximal size of each lines:

libtrary(stringr)

names <- list(
  "a" = "Nice table 1",
  "b" = "Here is a really long title that I would like to wrap within the facet pane")

labeller_fun <- 
  function(variable,value){
    return(str_wrap(names[value], width = 30))
  }

ggplot(gather(df, factor_key = TRUE), aes(x = factor(value))) + 
  geom_bar() + 
  facet_wrap(~ key, scales = "free_x", as.table = TRUE, labeller = labeller_fun) + 
  xlab("")

enter image description here

Does it answer your question ?

dc37
  • 15,840
  • 4
  • 15
  • 32