使用 aes_string 时如何包装 X 轴标签?

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

展示了如何在条形图中包装长标签。总之stringr::str_wrap。回顾:

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)

假设我正在使用 geom_histogram(stat="count") 来制作条形图,并且我正在使用 aes_string 因为我正在自动执行多个绘图。现在我该如何包装标签?

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)

但是

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

您可以将函数传递给 scale_x_discrete()labels 个参数。此功能将在绘图前应用于轴标签。

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