为facet_grid / facet_wrap绘图的每一行指定唯一宽度

问题描述 投票:5回答:2

我想为R中的一列,facet-wrapped图的每一行分配一个自定义宽度。(我知道这完全是非标准的。)

使用grid.arrange,我可以使用以下代码段为一个小平面包裹的图表的每一行分配一个唯一的高度:

group1 <- seq(1, 10, 2)
group2 <-  seq(1, 20, 3)
x = c(group1, group2)
mydf <- data.frame (X =x , Y = rnorm (length (x),5,1), 
                    groups = c(rep(1, length (group1)), rep(2, length(group2))))

plot1 <- ggplot(mydf, aes(X, Y)) + geom_point()
plot2 <- ggplot(mydf, aes(X, Y)) + geom_point()

grid.arrange(plot1, plot2, heights=c(1,2))

上面的代码为图的每一行提供了一个独特的高度:

enter image description here

我想知道是否可以为绘图的每一行指定一个唯一的宽度,而不是为每一行指定一个唯一的高度。是否可以使用任何ggplot2扩展名?

r ggplot2 plot visualization r-grid
2个回答
2
投票

是的,如果你在ggplot plot.margin中使用theme()功能,这是可能的。您可以通过执行以下操作将每个绘图宽度设置为页面总长度的百分比:

plot1 <- ggplot(mydf, aes(X, Y)) + geom_point()+theme( plot.margin = unit(c(0.01,0.5,0.01,0.01), "npc"))
plot2 <- ggplot(mydf, aes(X, Y)) + geom_point()+theme( plot.margin = unit(c(0.01,0.2,0.01,0.01), "npc"))

当我们在npc调用中使用plot.margins作为我们感兴趣的单位时,我们将相对于页面宽度进行设置。 0.50.2对应右边距。随着npc的增加,你的情节会越小。

grid.arrange(plot1, plot2, heights=c(1,2))

enter image description here


2
投票

作为另一种选择,您可以使用nullGrob(占用空间的空白grob)来分配给定行中的水平空间。例如:

library(gridExtra)
library(grid)

plot1 <- ggplot(mydf, aes(X, Y)) + geom_point()
plot2 <- ggplot(mydf, aes(X, Y)) + geom_point()

grid.arrange(arrangeGrob(plot1, nullGrob(), widths=c(1,1)), 
             plot2, heights=c(1,2))

enter image description here

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.