具有coord_fixed的多重布局

时间:2017-05-03 12:51:07

标签: r ggplot2

您可以对齐示例中的图,以便它们按顶部对齐吗? 这只是一个问题,因为我使用coord_fixed(但我需要)。

我的两个(小)文本标签应该显示,但这两个图放在单元格的垂直中心。

我看了看谷歌,我放弃了......

编辑以反映下面讨论的问题/解决方案:

library(ggplot2)
library(grid)
library(gridExtra)

plot1b = ggplot(mtcars, aes(mpg, wt)) + geom_point() + coord_fixed(ratio=5)
plot2b = ggplot(mtcars, aes(mpg, wt)) + geom_point() + coord_fixed(ratio=5) +
  facet_wrap( ~ cyl, ncol=2)

g1 = ggplotGrob(plot1b + theme(plot.margin = unit(c(0,0,0,0),'cm'), plot.background = element_rect(fill="red")))
g2 = ggplotGrob(plot2b + theme(plot.margin = unit(c(0,0,0,0),'cm'), plot.background = element_rect(fill="red")))
t1 = arrangeGrob(g1,left = textGrob("A", y=1, vjust=1, gp=gpar(fontsize=7, fontface="bold")))
t2 = arrangeGrob(g2,left = textGrob("B", y=1, vjust=1, gp=gpar(fontsize=7, fontface="bold")))
f1 = arrangeGrob(t1,t2, ncol=2)

g1 = ggplotGrob(plot1b + theme(plot.margin = unit(c(0,0,8,0),'cm'), plot.background = element_rect(fill="red")))
g2 = ggplotGrob(plot2b + theme(plot.margin = unit(c(0,0,8,0),'cm'), plot.background = element_rect(fill="red")))
t1 = arrangeGrob(g1,left = textGrob("A", y=1, vjust=1, gp=gpar(fontsize=7, fontface="bold")))
t2 = arrangeGrob(g2,left = textGrob("B", y=1, vjust=1, gp=gpar(fontsize=7, fontface="bold")))
f2 = arrangeGrob(t1,t2, ncol=2)

f3 =arrangeGrob(f1,f2,ncol=2)

plot(f3)
ggsave(plot=f3, file="plot.png")

enter image description here

2 个答案:

答案 0 :(得分:1)

试试这个(面板对齐,但不包括小平面条)

library(ggplot2)
library(grid)
library(gridExtra)

p1 = ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) + geom_point() + coord_fixed(ratio=1)+ theme(plot.background = element_rect(colour = "black"))
p2 = ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) + geom_point() + coord_fixed(ratio=1) +
  facet_wrap( ~ cyl, ncol=2) + theme(plot.background = element_rect(colour = "black"))

g1 = ggplotGrob(p1 )
g2 = ggplotGrob(p2)

g <- egg::ggarrange(p1, p2,ncol=2, draw = FALSE)
g <- gtable::gtable_add_grob(g, list(textGrob("A"), textGrob("B")), t = 1, l=c(1,4), z=-Inf)
grid.newpage()
grid.draw(g)

答案 1 :(得分:0)

我希望我理解你的问题。我在每个情节上添加了一个大的底部边距,将它们推到顶部。 (请注意,它实际上并没有像这张图片中那样被压扁)

library(ggplot2)
library(grid)
library(gridExtra)

plot1b = ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) + geom_point() + coord_fixed(ratio=1)+
  theme(plot.margin = unit(c(0,0,12,0),'cm'))
plot2b = ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) + geom_point() + coord_fixed(ratio=1) +
  facet_wrap( ~ cyl, ncol=2)+
  theme(plot.margin = unit(c(0,0,12,0),'cm'))

g1 = ggplotGrob(plot1b)
g2 = ggplotGrob(plot2b)
t1 = arrangeGrob(g1,left = textGrob("A", y=1, vjust=1, gp=gpar(fontsize=7, fontface="bold")))
t2 = arrangeGrob(g2,left = textGrob("B", y=1, vjust=1, gp=gpar(fontsize=7, fontface="bold")))
f1 = arrangeGrob(t1,t2, ncol=2)

plot(f1)

enter image description here