How to dynamically wrap facet label using ggplot2

前端 未结 4 919
余生分开走
余生分开走 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:14

    Also too long for a comment but no full answer. It goes along the lines of baptiste's answer, but with a few more pointers:

    p <- ggplot(df) + geom_point(aes(x=x, y=y)) + facet_wrap(~groupwrap)
    
    # get the grobs of the plot and get the widths of the columns
    grobs <- ggplotGrob(p)
    grobs$width
    
    # here you would have to use convertWidth from gridDebug package
    # to convert all the units in the widths to the same unit (say 'pt'),
    # including exctraction from the strings they are in -- also, I
    # couldn't make it work neither for the unit 'null' nor for 'grobwidth',
    # so you'll have to add up all the other ones, neglect grobwidth, and
    # subtract all the widths that are not null (which is the width of each
    # panel) from the device width
    library('grid')
    convertWidth(DO FOR EACH ELEMENT OF grobs$width)
    sum <- SUM_UP_ALL_THE_NON-PANEL_WIDTHS
    
    # get the width of the graphics device
    device <- par('din')[1]
    
    # get width of all panels in a row
    panels_width <- device - sum
    
    # get total number of panels in your case
    df$group <- as.factor(df$group)
    npanels <- nlevels(df$group)
    
    # get number of panels per row (i.e. number of columns in graph) with
    # the function that ggplot2 uses internally
    cols <- n2mfrow(npanels)
    
    # get estimate of width of single panel
    panel_width <- panels_width / cols
    

    Sorry that this is still patchy in parts. But that is as far as I got, so I hope these ideas might help along the way...

提交回复
热议问题