在gtable对象中设置宽度会折叠图; 这曾经工作但它不再存在.

Cla*_*lke 4 r ggplot2 gtable cowplot

以下代码用于工作但不再适用.有人知道发生了什么事吗?必须对基础gtable代码进行一些更改.

require(cowplot) # for plot_grid()
require(grid) # for unit_max()

# make two plots
plot.iris <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) + 
  geom_point() + facet_grid(. ~ Species) + stat_smooth(method = "lm") +
  background_grid(major = 'y', minor = "none") + 
  panel_border()
plot.mpg <- ggplot(mpg, aes(x = cty, y = hwy, colour = factor(cyl))) + 
  geom_point(size=2.5)

g.iris <- ggplotGrob(plot.iris) # convert to gtable
g.mpg <- ggplotGrob(plot.mpg) # convert to gtable

iris.widths <- g.iris$widths[1:3] # extract the first three widths, 
                                  # corresponding to left margin, y lab, and y axis
mpg.widths <- g.mpg$widths[1:3] # same for mpg plot
max.widths <- unit.pmax(iris.widths, mpg.widths) # calculate maximum widths
g.iris$widths[1:3] <- max.widths # assign max. widths to iris gtable
g.mpg$widths[1:3] <- max.widths # assign max widths to mpg gtable

plot_grid(g.iris, g.mpg, labels = "AUTO", ncol = 1)
Run Code Online (Sandbox Code Playgroud)

结果图如下: 在此输入图像描述

这应该是什么样的(y轴线完全垂直对齐): 在此输入图像描述

错误似乎发生在这一行:

g.iris$widths[1:3] <- max.widths
Run Code Online (Sandbox Code Playgroud)

任何见解将不胜感激.

注意,类似的解决方案已经使用了很长时间,参见例如此处.plot_grid()牛皮图中的函数也使用这样的代码来对齐绘图,它仍然有效.所以这让我完全神秘化了.

San*_*att 7

编辑
使用grid3.3.0版本,这不再是一个问题.也就是说,grid:::unit.list()可以删除包含以下内容的代码行.

问题与设置单位的方式有关.看看g.iris$widths.您会注意到数字在那里,但单位已被删除.看到这个问题和答案,以及这一个.将图表转换为gtables后,您需要:g.iris$widths = grid:::unit.list(g.iris$widths)

require(grid) # for unit_max()
require(cowplot)

# make two plots
plot.iris <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) + 
  geom_point() + facet_grid(. ~ Species) + stat_smooth(method = "lm") + 
  background_grid(major = 'y', minor = "none") + 
  panel_border()
plot.mpg <- ggplot(mpg, aes(x = cty, y = hwy, colour = factor(cyl))) + 
  geom_point(size=2.5) 

g.iris <- ggplotGrob(plot.iris) # convert to gtable   
g.mpg <- ggplotGrob(plot.mpg) # convert to gtable

g.iris$widths = grid:::unit.list(g.iris$widths)   
g.mpg$widths =  grid:::unit.list(g.mpg$widths)

iris.widths <- g.iris$widths[1:3] # extract the first three widths, 
                                  # corresponding to left margin, y lab, and y axis
mpg.widths <- g.mpg$widths[1:3] # same for mpg plot

max.widths <- unit.pmax(iris.widths, mpg.widths) # calculate maximum widths

g.iris$widths[1:3] <- max.widths # assign max. widths to iris gtable
g.mpg$widths[1:3] <- max.widths # assign max widths to mpg gtable

plot_grid(g.iris, g.mpg, labels = "AUTO", ncol = 1)
Run Code Online (Sandbox Code Playgroud)

  • 实际上,`grid ::: unit.list()`已经需要一段时间了; 当我开始注意到ggplot2破损时,我忘记了.这种未导出的网格功能几乎成为进行这种绘图对齐的要求,这在包中可能是有问题的. (2认同)