如何在多个多面ggplot2图形中实现相同的面大小和缩放比例? [英] How achieve identical facet sizes and scales in several multi-facet ggplot2 graphics?

查看:222
本文介绍了如何在多个多面ggplot2图形中实现相同的面大小和缩放比例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一系列 ggplot2 图形,它们具有恒定数量的水平面但不同数量的垂直面。我希望将格式保存为.pdf,格式为a4格式。

I have a series of ggplot2 graphics with a constant number of horizontal but differing number of vertical facets. I would like to save the graphics as .pdf on landscape a4 format.

然而,我不知道如何实现相同比例的方面。如果我尝试手动调整它,并针对不同数量的垂直刻面更改 width height ,则刻度会在不同的图,即我得到不同的磅值和线宽。

However, I don't know how I can achieve identical proportions of the facets. If I try to tweak it manually and vary width and height for different numbers of vertical facets, the scales vary between plots, i.e., I get different points sizes and line widths.

从本质上说,我可以如何实现具有可变数量(垂直)面的图的相同面尺寸和比例尺?

In essence, how can I achieve identical facets sizes and scales for plots with a variable number of (vertical) facets?

以下是一个例子:

Here is an example:

df <- expand.grid(a = 1:2, b = 1:5, x = 1:10)
df$y <- df$x
plot <- ggplot(data = df, mapping = aes(x = x, y = y)) +
            geom_point()
plot1 <- plot + facet_grid(facets = "a ~ b")
plot2 <- plot + facet_grid(facets = ". ~ b")

ggsave(filename = "./figures/plot1.pdf", plot = plot1,
   height = 210, width = 297, units = "mm")

ggsave(filename = "./figures/plot2.pdf", plot = plot2,
   height = 210, width = 297, units = "mm")


推荐答案

我使用此代码设置面板大小为绝对值,也许它在这里有帮助

I use this code to set panel sizes to absolute values, maybe it helps here

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))

  invisible(g)
}

print.fixed <- function(x) grid.draw(x)

这篇关于如何在多个多面ggplot2图形中实现相同的面大小和缩放比例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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