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

标签 r ggplot2 axis-labels

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))

enter image description here

关于r - 使用 aes_string 时如何包装 X 轴标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61782882/

相关文章:

r - 合并 3 个数据框左连接

r - 实现平滑的色带

r - 如何将 ggplot 对象存储在 R 的数据框中?

javascript - 为什么 jqPlot 轴刻度文本标签被裁剪/损坏并且轴标签不显示?

r - 即使数据很小 : Error in mcfork() : unable to fork, 可能的原因:无法分配内存

html - 如何在shiny中设置尺寸和特定布局

r - 在运行时在 lapply 包装器中打印消息

r - 用 hexSticker 修剪六边形形状?

python - cartopy set_xlabel set_ylabel(不是刻度标签)

r - 如何在R条形图中显示所有x标签?