将两个ggplots组合成一个x轴和两个y轴

时间:2017-01-10 19:49:07

标签: r ggplot2

我想结合ggplots。我尝试了以下代码,但结果不是很好。在联合图中,我遇到了第二个y轴和图1的错误栏的问题。

Plot 1

pdf(file=paste("./plots/", "Cog1rt.pdf", sep=""), width=16, height=11)
p1 <- ggplot(data=datcom, aes(x=group, y=value, fill=group)) +
  geom_bar(position="dodge", size=.3,stat="identity") +  
  geom_errorbar( aes(ymax=value+1*value2, ymin=value, width=0.1,colour=group)) +
  labs(x="\n Gruppe", y="Reaktionszeit\n") + 
  facet_wrap(~rt) +
  theme_bw() %+replace%  theme(panel.background = element_rect(fill = NA))
print(p1) 
dev.off()

Plot 2

pdf(file="./plots/Cog1errl.pdf", width=4, height=3.5)
p2 <- ggplot(data=datcom, aes(x=group, y=value3,fill=group)) +

  geom_errorbar(aes(ymax=value3+1*value4, ymin=value3-1*value4,width=0.6)) +
  geom_point() +
  facet_wrap(~rt) +
  ylab("Fehler") +
  theme_bw() %+replace%  theme(panel.background = element_rect(fill = NA))
print(p2)

dev.off()

联合

g1 <- ggplot_gtable(ggplot_build(p1))
g2 <- ggplot_gtable(ggplot_build(p2))

pp <- c(subset(g1$layout, grepl("panel",name) , se = t:r))

g <- gtable_add_grob(g1, g2$grobs[grep("panel",g2$layout$name)], pp$t, 
                     pp$l, pp$b, pp$l)
ia <- which(grepl("axis_l",g2$layout$name) |  grepl("axis-l",g2$layout$name)     )
ga <- g2$grobs[ia]

axis_idx <- as.numeric(which(sapply(ga,function(x) !is.null(x$children$axis))))

i <- length(axis_idx)
ax <- ga[[axis_idx[i]]]$children$axis
ax$widths <- rev(ax$widths)
ax$grobs <- rev(ax$grobs)
ax$grobs[[1]]$x <- ax$grobs[[1]]$x - unit(-0.8, "npc") + unit(-0.1, "cm")
g <- gtable_add_cols(g, g2$widths[12], 12)
g <- gtable_add_grob(g, ax, pp$t[axis_idx[i]], length(g$widths) - 3, pp$b[axis_idx[i]])
grid.newpage()
grid.draw(g)

0 个答案:

没有答案