Search code examples
rggplot2axis-labels

How to wrap an X-axis label when using aes_string?


This lovely answer shows how to wrap long labels in a bar chart. In short stringr::str_wrap. Recap:

V1 <- c("Long label", "Longer label", "An even longer label",
        "A very, very long label", "An extremely long label",
        "Long, longer, longest label of all possible labels", 
        "Another label", "Short", "Not so short label")
df <- data.frame(V1, V2 = nchar(V1))
yaxis_label <- "A rather long axis label of character counts"
library(ggplot2)  # version 2.2.0+
p <- ggplot(df, aes(V1, V2)) + geom_col() + xlab(NULL) +
  ylab(yaxis_label) 
p + aes(stringr::str_wrap(V1, 15), V2) + xlab(NULL) +
  ylab(yaxis_label)

Suppose I'm using geom_histogram(stat="count") to make the bars, and I'm using aes_string because I'm automating multiple plots. Now how do I wrap the labels?

df2 <- data.frame(V1=rep(df$V1, df$V2))
# works
q <- ggplot(df2, aes(V1)) + geom_histogram(stat="count") + xlab(NULL) +
  ylab(yaxis_label)
q + aes(stringr::str_wrap(V1, 15)) + xlab(NULL) +
  ylab(yaxis_label)

but

# doesn't wrap
r <- ggplot(df2, aes_string(stringr::str_wrap(varname, 15))) +
  geom_histogram(stat="count") + xlab(NULL) +
  ylab(yaxis_label) 
r

Solution

  • You can pass a function to the labels arguments of scale_x_discrete(). This function will be applied to the axis labels before plotting.

    ggplot(df2, aes_string("V1")) +
      geom_bar() +
      scale_x_discrete(labels = function(x) stringr::str_wrap(x, width = 10))
    

    enter image description here