【发布时间】:2020-05-13 19:05:56
【问题描述】:
This lovely answer 展示了如何在条形图中包裹长标签。简而言之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
【问题讨论】:
标签: r ggplot2 axis-labels