0

I want to wrap long category labels on my ggplot in R. I know I can use str_wrap() and scale_x_manual() to wrap them onto a new line after, say 10 words. However, several of my category labels are king strings of continuous characters, without spaces (eg they have underscores instead of spaces). How can I wrap onto new lines after, say 40 characters?

Here's an example

df = data.frame(x = c("label", "long label with spaces", "long_label_with_no_spaces_in_it_which_is_too_lon"), 
                y = c(10, 15, 20))

ggplot(df, aes(x, y)) +
  geom_bar(stat = "identity") +
  scale_x_discrete(labels = function(x) str_wrap(x, width = 10))
Mike
  • 921
  • 7
  • 26

2 Answers2

1

Convert the underscores to spaces, then str_wrap, then replace spaces with underscores:

ggplot(df, aes(x, y)) +
  geom_bar(stat = "identity") +
  scale_x_discrete(labels = ~ gsub(' ', '_', str_wrap(gsub('_', ' ', .x), 40)))

enter image description here

Though to be honest, I think it looks more professional to not bother replacing the underscores:

ggplot(df, aes(x, y)) +
  geom_bar(stat = "identity") +
  scale_x_discrete(labels = ~ str_wrap(gsub('_', ' ', .x), 20))

enter image description here

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
0

I would add code where you change the underscore to a space if all examples are as you stated.

df = data.frame(x = c("label", "long label with spaces", "long_label_with_no_spaces_in_it_which_is_too_lon"), 
            y = c(10, 15, 20))

df$x <- gsub("_"," ",df$x)

ggplot(df, aes(x, y)) +
  geom_bar(stat = "identity") +
  scale_x_discrete(labels = function(x) str_wrap(x, width = 10))

If you really want to add a break after i.e. 10 characters, perhaps this code can work:

df$x<- insert_line_breaks(df$x, width = 10)
PeSkoog
  • 1
  • 2