我正在使用ggplot2在双轴上绘图。我正在使用下面发布的代码。我试图将它保存为JPEG,但它只保存最后一行输出,而不是曲线的两行,即使轴是正确的。如何在同一时间用相对线保存两个轴?我正在尝试ggsave,但它抱怨它不是ggplot2格式。ggplot2双轴。不可能保存到文件
## Putting plots together ##################
# extract gtable
g1 <- ggplot_gtable(ggplot_build(p1))
g2 <- ggplot_gtable(ggplot_build(p2))
# overlap the panel of 2nd plot on that of 1st plot
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)
# axis tweaks
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))))
for(i in 1: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(1, "npc") + unit(0.15, "cm")
g <- gtable_add_cols(g, g2$widths[g2$layout[ia[axis_idx[i]], ]$l], length(g$widths) - 1)
g <- gtable_add_grob(g, ax, pp$t[axis_idx[i]], length(g$widths) - i, pp$b[axis_idx[i]])
}
# Plot!
grid.newpage()
grid.draw(g)
也许你的第二个阴谋不透明?尝试'g2 < - ggplot_gtable(ggplot_build(p2 + theme(plot.background = element_blank(),panel.background = element_blank())))' – inscaven
不,它似乎总是只保存两个绘图中的一个。不是都。我试过了你的建议,但结果是一样的。 – user1176316
您还需要打开具有像'jpeg(bg =“transparent”)''的透明图形设备,默认情况下它具有'bg =“white”' – inscaven