How can I remove empty factors from ggplot2 facets?

后端 未结 2 1177
一个人的身影
一个人的身影 2020-11-27 06:18

I\'m trying to modify an example of a simple forest plot by introducing facets according to a factor variable.

Assuming data of this structure:

test         


        
相关标签:
2条回答
  • 2020-11-27 06:39

    EDIT Updated to ggplot2 0.9.3

    Here's another solution. It uses facet_grid and space = "free"; also it uses geom_point() and geom_errorbarh(), and thus there is no need for coord.flip(). Also, the x-axis tick mark labels appear on the lower panel only. In the code below, the theme command is not essential - it is used to rotate the strip text to appear horizontally. Using the test dataframe from above, the following code should produce what you want:

    library(ggplot2)
    
    p <- ggplot(test, aes(y = characteristic, x = es, xmin = ci_low, xmax = ci_upp)) +
       geom_point() +
       geom_errorbarh(height = 0) +
       facet_grid(set ~ ., scales = "free", space = "free") +
       theme_bw() +
       theme(strip.text.y = element_text(angle = 0))
    
    p
    

    The solution is based on the example on page 124 in Wickham's ggplot2 book.

    0 讨论(0)
  • 2020-11-27 06:43

    Use scales = "free" as in:

    p <- ggplot(test, aes(x=characteristic, y=es, ymin=ci_low, ymax=ci_upp)) + geom_pointrange() +
      coord_flip() + geom_hline(aes(x=0), lty=2) + 
      facet_wrap(~ set, ncol = 1, scales="free") +
      theme_bw() + 
      opts(strip.text.x = theme_text())
    
    p
    

    Which produces:

    enter image description here

    EDIT: I actually think I like the drop = TRUE argument better for this solution as in:

    p <- ggplot(test, aes(x=characteristic, y=es, ymin=ci_low, ymax=ci_upp)) + 
      geom_pointrange() +
      coord_flip() + geom_hline(aes(x=0), lty=2) + 
      facet_wrap(~ set, ncol = 1,  drop=TRUE) +
      theme_bw() + 
      opts(strip.text.x = theme_text())
    
    p
    
    0 讨论(0)
提交回复
热议问题