R: ggplot2, can I make the facet/strip text wrap a

2019-05-03 07:43发布

I found this very useful code for wrapping text here:

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

I would like to use it to wrap the text in a facet/strip but don't know how.

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

Is it passed to the strip.text.x options?

标签: r ggplot2
2条回答
放荡不羁爱自由
2楼-- · 2019-05-03 08:29

Since this question was posted, the new label_wrap_gen() function with ggplot2 (>= 1.0.0, I think) handles this nicely:

facet_wrap(~variable1, labeller = label_wrap_gen())
查看更多
Deceive 欺骗
3楼-- · 2019-05-03 08:36

my best guess would be to define a custom theme_text for the strip label,

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

 p + opts(strip.text.x = theme_splittext())

quick testing reveals that the width of each line doesn't necessarily fit in the facet strip, however; a better approach might be to use splitTextGrob from RGraphics where the splitting is done at drawing time to fit in the current viewport,

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

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


 heightDetails.splitText = function(x) unit(2, "lines")

The problem is that ggplot expects the grob to know its size, whilst the grob expects a viewport with specific dimensions... It would generally require some sort of prior estimate, but in practical terms I don't think you want more than two lines of text.

查看更多
登录 后发表回答