使用ggplot制作的分面图如何自动裁剪?

4

在使用ggplot绘制分面图并改变纵横比时,通常会出现大量的空白,要么是左右两侧,要么是上下两端。例如:

library(ggplot2)
df <- data.frame(x=rep(1,3), y=rep(1,3), z=factor(letters[1:3]))
p <- ggplot(df, aes(x, y)) + geom_point() + coord_fixed(ratio=1) + facet_grid(z ~ .)
ggsave("plot.jpg", p, scale=1, device="jpeg")

有没有自动裁剪图表的方法?


你是指分面图之间的空白,还是整个图周围的空白?对于前者,这些应该有所帮助:https://dev59.com/mGAg5IYBdhLWcg3w_fLV和https://dev59.com/AIzda4cB1Zd3GeqPjzwt。对于后者,我认为ggsave默认使用当前图形设备的尺寸,除非您指定高度和宽度。您是否正在寻找一种自动基于您的绘图获取合理高度/宽度规格的方法? - Z.Lin
1
我指的是整个图形周围的空间。我非常希望能够自动获取ggsave的高度/宽度规格的方法。 - WJH
1个回答

3

以下是我想到的内容。我在您的样例上进行了测试,看起来可以正常工作,但如果在其他地方出现问题,请提前谅解。我不得不深入到grob版本中获取宽度/高度信息,并根据图形是否被分面,"unit"属性信息位于不同的位置。

希望更熟悉grid包中unit对象的人能够给予帮助,以下是我的成果:

# Note that you need to set an upper limit to the maximum height/width
# that the plot can occupy, in the max.dimension parameter (defaults to
# 10 inches in this function)

ggsave_autosize <- function(filename, plot = last_plot(), device = NULL, path = NULL, scale = 1, 
                            max.dimension = 10, units = c("in", "cm", "mm"), 
                            dpi=300, limitsize = TRUE){

  sumUnitNull <- function(x){
    res <- 0
    for(i in 1:length(x)){ 
      check.unit <- ifelse(!is.null(attr(x[i], "unit")), attr(x[i], "unit"), 
                           ifelse(!is.null(attr(x[i][[1]], "unit")), attr(x[i][[1]], "unit"), NA))
      if(!is.na(check.unit) && check.unit == "null") res <- res + as.numeric(x[i])
    }
    return(res)
  }

  # get width/height information from the plot object (likely in a mixture of different units)
  w <- ggplotGrob(plot)$widths
  h <- ggplotGrob(plot)$heights

  # define maximum dimensions
  w.max <- grid::unit(max.dimension, units) %>% grid::convertUnit("in") %>% as.numeric()
  h.max <- grid::unit(max.dimension, units) %>% grid::convertUnit("in") %>% as.numeric()

  # sum the inflexible size components of the plot object's width/height 
  # these components have unit = "in", "mm", "pt", "grobheight", etc
  w.in <- w %>% grid::convertUnit("in") %>% as.numeric() %>% sum()
  h.in <- h %>% grid::convertUnit("in") %>% as.numeric() %>% sum()

  # obtain the amount of space available for the flexible size components
  w.avail <- w.max - w.in
  h.avail <- h.max - h.in

  # sum the flexible sized components of the plot object's width/height 
  # these components have unit = "null"
  w.f <- sumUnitNull(w)
  h.f <- sumUnitNull(h)

  # shrink the amount of avilable space based on what the flexible components would actually take up
  if(w.f/h.f > w.avail/h.avail) h.avail <- w.avail/w.f*h.f else w.avail <- h.avail/h.f*w.f

  w <- w.in + w.avail
  h <- h.in + h.avail

  ggsave(filename, plot = plot, device = device, path = path, scale = scale,
         width = w, height = h, units = units, dpi = dpi, limitsize = limitsize)
}


p <- ggplot(mpg, aes(displ, cty)) + geom_point() + coord_fixed(ratio=1)
p <- p + facet_grid(. ~ cyl)

ggsave("pOriginal.png", p + ggtitle("original"))
ggsave_autosize("pAutoSize.png", p + ggtitle("auto-resize"))
ggsave_autosize("pAutoSize8.png", p + ggtitle("auto-resize, max dim = 8in x 8in"), max.dimension = 8, units = "in")

原始版本未裁剪。左/右侧有黑色空间:

original

自动裁剪版本。高度=10英寸:

autosize

自动裁剪版本。高度=8英寸(因此字体看起来稍微大一些):

autosize2


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接