【问题标题】:Automatically wrapping long pane titles in facet_wrap [duplicate]在 facet_wrap 中自动包装长窗格标题 [重复]
【发布时间】:2020-04-21 05:36:40
【问题描述】:

我想用 facet_wrap 总结几列。我想给几个方面窗格长标题。例如:

set.seed(123)

df <- 
  data.frame(
    a = sample(0:1, 20, replace = T),
    b = sample(1:4, 20, replace = T)
  )

names <- list(
  "a" = "Nice table 1",
  "b" = "Here is a really long title that I would like to wrap within the facet pane")

labeller_fun <- 
  function(variable,value){
  return(names[value])
  }

ggplot(gather(df,, factor_key = TRUE), aes(x = factor(value))) + 
geom_bar() + 
facet_wrap(~ key, scales = "free_x", as.table = TRUE, labeller = labeller_fun) + 
xlab("")

在这里,长标题溢出并且大部分是不可见的。有没有办法在窗格标题框中自动换行长文本?

【问题讨论】:

    标签: r ggplot2 tidyverse


    【解决方案1】:

    您可以使用 stringr 包中的函数 str_wrap 并将其添加到“labeller_fun”函数的返回值中。

    使用参数width,可以指定每行的最大尺寸:

    libtrary(stringr)
    
    names <- list(
      "a" = "Nice table 1",
      "b" = "Here is a really long title that I would like to wrap within the facet pane")
    
    labeller_fun <- 
      function(variable,value){
        return(str_wrap(names[value], width = 30))
      }
    
    ggplot(gather(df, factor_key = TRUE), aes(x = factor(value))) + 
      geom_bar() + 
      facet_wrap(~ key, scales = "free_x", as.table = TRUE, labeller = labeller_fun) + 
      xlab("")
    

    它回答了你的问题吗?

    【讨论】:

      猜你喜欢
      • 2021-12-11
      • 1970-01-01
      • 2019-10-09
      • 2010-12-01
      • 2013-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多