在ggplot2中设置facets的绝对大小 [英] Setting absolute size of facets in ggplot2

查看:137
本文介绍了在ggplot2中设置facets的绝对大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为报告创建了多个方面的图。理想情况下,我希望每个方面的绝对尺寸相同(例如4x4厘米),以便比较它们更容易(而且它看起来更好看)。

I'm creating several facetted plots for a report. The number of facets varies between 2 and 8. Ideally, I'd like the absolute size of each facet (across plots) to be the same (e.g. 4x4 cm) so that it is easier to compare them (and it looks nicer, too).

这可能吗?

df1 <- structure(list(group1 = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,1L, 1L, 1L, 1L, 1L), .Label = c("S1", "S2"), class = "factor"), group = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L), .Label = c("A", "B", "C", "D", "E"), class = "factor"), value = 1:12), class = "data.frame", row.names = c(NA, -12L), .Names = c("group1", "group", "value"))

df2 <- structure(list(group1 = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("S1", "S2"), class = "factor"), group = structure(c(4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L), .Label = c("A", "B", "C", "D", "E"), class = "factor"), value = 13:20), class = "data.frame", row.names = c(NA, -8L), .Names = c("group1", "group", "value"))

library(ggplot2)

plot1 <- ggplot(df1) + geom_histogram(aes(x=value)) + facet_wrap(~group)
plot2 <- ggplot(df2) + geom_histogram(aes(x=value)) + facet_wrap(~group)

推荐答案

这个目的,

I've used the following function for this purpose,

set_panel_size <- function(p=NULL, g=ggplotGrob(p), file=NULL, 
                           margin = unit(1,"mm"),
                           width=unit(4, "cm"), 
                           height=unit(4, "cm")){

  panels <- grep("panel", g$layout$name)
  panel_index_w<- unique(g$layout$l[panels])
  panel_index_h<- unique(g$layout$t[panels])
  nw <- length(panel_index_w)
  nh <- length(panel_index_h)

if(getRversion() < "3.3.0"){

   # the following conversion is necessary
   # because there is no `[<-`.unit method
   # so promoting to unit.list allows standard list indexing
   g$widths <- grid:::unit.list(g$widths)
   g$heights <- grid:::unit.list(g$heights)

   g$widths[panel_index_w] <-  rep(list(width),  nw)
   g$heights[panel_index_h] <- rep(list(height), nh)

} else {

   g$widths[panel_index_w] <-  rep(width,  nw)
   g$heights[panel_index_h] <- rep(height, nh)

}

  if(!is.null(file))
    ggsave(file, g, 
           width = convertWidth(sum(g$widths) + margin, 
                                unitTo = "in", valueOnly = TRUE),
           height = convertHeight(sum(g$heights) + margin,  
                                  unitTo = "in", valueOnly = TRUE))

  g
}

g1 <- set_panel_size(plot1)
g2 <- set_panel_size(plot2)
grid.arrange(g1,g2)

这篇关于在ggplot2中设置facets的绝对大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆