在如何将转换后的比例放在 ggplot2 的右侧?展示了如何通过操纵 ggplot2 对象并将其与 gtable 合并来在同一个图中添加两个 y 轴。从那里的示例中,我设法将其扩展为与 facet_wrap 一起使用。请参见下面的示例。
然而,有三件事并不完美。
- 天平总是放在最右边。如果它与最后一行的情节联系起来会更好
scales="free_y"
如果所有图上分别有 y 轴(即您输入facet_wrap
),则它不起作用- 如果我将网格线留在(注释掉的线)中,第二个图的网格线出现在第一个图的前面。
如果有解决这些公认的小问题的聪明方法有什么想法吗?
library(ggplot2)
library(gtable)
library(grid)
p1 <- ggplot(diamonds, aes(y=carat,x=price))
p1 <- p1 + geom_point(color="red")
p1 <- p1 + facet_wrap(~ color)
p1 <- p1 + theme_bw() %+replace% theme(panel.background = element_rect(fill = NA)) # use white theme and set bg to transparent so they can merge nice
#p1 <- p1 + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) # remove gridlines
p1
p2 <- ggplot(diamonds, aes(x=price))
p2 <- p2 + geom_histogram( binwidth = 1000)
p2 <- p2 + facet_wrap(~ color)
p2 <- p2 + theme_bw() %+replace% theme(panel.background = element_rect(fill = NA))
#p2 <- p2 + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())
p2
## 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)