How to dynamically wrap facet label using ggplot2

前端 未结 4 926
余生分开走
余生分开走 2020-12-14 15:52

I\'m looking for a way to dynamically wrap the strip label text in a facet_wrap or facet_grid call. I\'ve found a way to accomplish this using

4条回答
  •  隐瞒了意图╮
    2020-12-14 16:03

    (too long as a comment, but not a real answer either)

    I don't think a general solution will exist directly within ggplot2; it's the classic problem of self-reference for grid units: ggplot2 wants to calculate the viewport sizes on-the-fly, while the strwrap would need to know a firm width to decide how to split the text. (there was a very similar question, but I forget when and where).

    You could however write a helping function to estimate how much wrapping you'll need before plotting. In pseudo code,

    # takes the facetting variable and device size
    estimate_wrap = function(f, size=8, fudge=1){ 
    
        n = nlevels(f)
        for (loop over the labels of strwidth wider than (full.size * fudge) / n){
         new_factor_level[ii] = strwrap(label[ii], available width)
        }
    
      return(new_factor)
    }
    

    (with some standard unit conversions required)

    Of course, things would get more complicated if you wanted to use space="free".

提交回复
热议问题