【问题标题】:How to wrap an X-axis label when using aes_string?使用 aes_string 时如何包装 X 轴标签?
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-07
      • 2020-09-14
      • 1970-01-01
      • 2012-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多