请问ggplot2可以绘制双坐标图吗?就是左右两边可以显示不同坐标轴的……求问方法,谢谢

http://stackoverflow.com/questions/3099219/how-to-use-ggplot2-make-plot-with-2-y-axes-one-y-axis-on-the-left-and-another

参见第二条回答,H大亲自上阵解答。

回复 第2楼 的 Peter Chen:好强大的帖……不过感到在度量单位不一样&想比较关于同一个变量的走势&想节省空间的前提下……还是有必要的(实际我正是这些需求……TT)

4 个月 后
8 天 后

回复 第4楼 的 Perry:这个办法里如果想要画各分面做双坐标怎么弄呢?我照着rups里的代码改了一下,其实不知道太多的知识,因为涉及到grid和gtable这两个包,觉得学起来太花时间了。就想着照猫画虎能实现最好。

<br />
p1 <- ggplot(mtcars, aes(mpg, disp)) + geom_line(colour = "blue") + theme_bw()+facet_wrap(~vs)<br />
p2 <- ggplot(mtcars, aes(mpg, drat)) + geom_line(colour = "red") + theme_bw() %+replace%<br />
  theme(panel.background = element_rect(fill = NA))+facet_wrap(~vs)<br />
# extract gtable<br />
g1 <- ggplot_gtable(ggplot_build(p1))<br />
g2 <- ggplot_gtable(ggplot_build(p2))</p>
<p># overlap the panel of 2nd plot on that of 1st plot<br />
#pp <- c(subset(g1$layout, name == "panel", se = t:r))<br />
pp <- c(subset(g1$layout, name %in% g1$layout$name[2:3] , se = t:r))<br />
# g <- gtable_add_grob(g1, g2$grobs[[which(g2$layout$name == "panel")]], pp$t,<br />
#                      pp$l, pp$b, pp$l)<br />
g <- gtable_add_grob(g1, g2$grobs[2:3], pp$t,<br />
                     pp$l, pp$b, pp$l)</p>
<p>


到这里还没什么,我用自己的数据测试了如下这一段代码,没什么问题,用的mtcars就出问题了,还没找到问题。</p>

<br />
ia <- which(g2$layout$name %in%  g2$layout$name[6:7])<br />
ga=list();ax=list()<br />
for(i in 1:length(ia)){<br />
  ga[[i]] <- g2$grobs[[i+6-1]]<br />
  ax[[i]] <- ga[[i]]$children[[2]]<br />
  ax[[i]]$widths <- rev(ax[[i]]$widths)<br />
  ax[[i]]$grobs <- rev(ax[[i]]$grobs)<br />
  ax[[i]]$grobs[[1]]$x <- ax[[i]]$grobs[[1]]$x - unit(1, "npc") + unit(0.15, "cm")<br />
}<br />
g <- gtable_add_cols(g, g2$widths[g2$layout[ia, ]$l], length(g$widths) - 1)<br />
g <- gtable_add_grob(g, ax, pp$t, length(g$widths) - 1, pp$b)</p>
<p># draw it<br />
grid.draw(g)<br />


我用自己画出来的图,是可以分面,两轴数据都在,但是第二个y轴在剧靠右边,不知道怎么调整。

这是图片地址(此图是我的数据,这里是用mtcar做演示)http://ww3.sinaimg.cn/large/61830b46jw1e79hvpnnauj21hc0sa7d8.jpg。请大神指导
</p>