ggplot2: More complex faceting

前端 未结 2 1798
别那么骄傲
别那么骄傲 2020-12-10 16:49

I have a heatmap that continues to become more and more complex. An example of the melted data:

head(df2)
  Class     Subclass         Family                        


        
相关标签:
2条回答
  • 2020-12-10 17:10

    Turning my comment into an answer with some simple demo data:

    This isn't hard (there's even examples in ?facet_grid, though they're towards the bottom).

    # generate some nested data
    dat = data.frame(x = rnorm(12), y = rnorm(12), class = rep(LETTERS[1:2], each = 6),
                     subclass = rep(letters[1:6], each = 2))
    
    # plot it
    ggplot(dat, aes(x, y)) + geom_point() +
        facet_grid(subclass + class ~ .)
    

    You can do this with arbitrarily many factors on either side of the ~!

    0 讨论(0)
  • 2020-12-10 17:17

    This will put a new strip to the right of the orignal strip, and to the left of the legend.

    library(ggplot2)
    library(gtable)
    library(grid)
    
    p <- ggplot(mtcars, aes(mpg, wt, colour = factor(vs))) + geom_point()
    p <- p + facet_grid(cyl ~ gear)
    
    # Convert the plot to a grob
    gt <- ggplotGrob(p)
    
    # Get the positions of the right strips in the layout: t = top, l = left, ...
    strip <-c(subset(gt$layout, grepl("strip-r", gt$layout$name), select = t:r))
    
    #  New column to the right of current strip
    gt <- gtable_add_cols(gt, gt$widths[max(strip$r)], max(strip$r))  
    
    # Add grob, the new strip, into new column
    gt <- gtable_add_grob(gt, 
      list(rectGrob(gp = gpar(col = NA, fill = "grey85", size = .5)),
      textGrob("Number of Cylinders", rot = -90, vjust = .27, 
            gp = gpar(cex = .75, fontface = "bold", col = "black"))), 
            t = min(strip$t), l = max(strip$r) + 1, b = max(strip$b), name = c("a", "b"))
    
    # Add small gap between strips
    gt <- gtable_add_cols(gt, unit(1/5, "line"), max(strip$r))
    
    # Draw it
    grid.newpage()
    grid.draw(gt)
    

    enter image description here

    0 讨论(0)
提交回复
热议问题