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
最佳答案
您可以将函数传递给 labels
scale_x_discrete()
的参数.此函数将在绘图前应用于轴标签。
ggplot(df2, aes_string("V1")) +
geom_bar() +
scale_x_discrete(labels = function(x) stringr::str_wrap(x, width = 10))
关于r - 使用 aes_string 时如何包装 X 轴标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61782882/