R:ggplot2,我可以将facet/strip文本换行吗?

ali*_*nk8 5 r ggplot2

我发现这是非常有用的代码文本换行位置:

 wrapper <- function(x, ...) paste(strwrap(x, ...), collapse = "\n")`

 my_title <- "This is a really long title of a plot that I want to nicely wrap and fit onto the plot without having to manually add the backslash n, but at the moment it does not"

 r + geom_smooth() + opts(title = wrapper(my_title, width = 20))
Run Code Online (Sandbox Code Playgroud)

我想用它来将文本包装在一个方面/条带中,但不知道如何.

 p + geom_bar(stat="identity")+facet_wrap(~variable1) + 
    opts(strip.text.x=theme_text(size=12, face="bold")
Run Code Online (Sandbox Code Playgroud)

它是否传递给strip.text.x选项?

Cep*_*irk 7

自从这个问题发布以来,label_wrap_gen()带有ggplot2(> = 1.0.0,我认为)的新函数处理得很好:

facet_wrap(~variable1, labeller = label_wrap_gen())
Run Code Online (Sandbox Code Playgroud)


bap*_*ste 3

我最好的猜测是为条带标签定义一个自定义 theme_text ,

 theme_splittext = function (...) 
 {
   function(label, ...) {
    splitlab = paste(strwrap(label), collapse="\n")
         textGrob(splitlab, 0.5, 0.5,  ...) 
         }
 }

 p + opts(strip.text.x = theme_splittext())
Run Code Online (Sandbox Code Playgroud)

然而,快速测试表明,每条线的宽度不一定适合刻面条;更好的方法可能是使用 RGraphics 中的 splitTextGrob,其中分割是在绘图时完成的,以适合当前视口,

 theme_splittext2 = function (...) 
 {
    require(RGraphics)
   function(label, ...) {

    splitTextGrob(label, ..., vp=viewport(height=unit(2, "lines")))
         }
 }


 heightDetails.splitText = function(x) unit(2, "lines")
Run Code Online (Sandbox Code Playgroud)

问题是 ggplot 期望 grob 知道它的大小,而 grob 期望一个具有特定尺寸的视口......它通常需要某种事先估计,但实际上我认为你不需要超过两行的文本。