楼主: famousid
13895 7

[程序分享] ggplot2 绘制双坐标图 [推广有奖]

  • 1关注
  • 17粉丝

已卖:96份资源

硕士生

90%

还不是VIP/贵宾

-

威望
0
论坛币
3449775 个
通用积分
2.9994
学术水平
51 点
热心指数
53 点
信用等级
41 点
经验
3818 点
帖子
182
精华
0
在线时间
198 小时
注册时间
2009-12-9
最后登录
2017-9-10

楼主
famousid 发表于 2013-4-25 23:27:39 |AI写论文

+2 论坛币
k人 参与回答

经管之家送您一份

应届毕业生专属福利!

求职就业群
赵安豆老师微信:zhaoandou666

经管之家联合CDA

送您一个全额奖学金名额~ !

感谢您参与论坛问题回答

经管之家送您两个论坛币!

+2 论坛币
  1. library(ggplot2)
  2. library(gtable)
  3. library(grid)

  4. grid.newpage()

  5. # two plots
  6. p1 <- ggplot(mtcars, aes(mpg, disp)) + geom_line(colour = "blue") + theme_bw()
  7. p2 <- ggplot(mtcars, aes(mpg, drat)) + geom_line(colour = "red") + theme_bw() %+replace%
  8.     theme(panel.background = element_rect(fill = NA))

  9. # extract gtable
  10. g1 <- ggplot_gtable(ggplot_build(p1))
  11. g2 <- ggplot_gtable(ggplot_build(p2))

  12. # overlap the panel of 2nd plot on that of 1st plot
  13. pp <- c(subset(g1$layout, name == "panel", se = t:r))
  14. g <- gtable_add_grob(g1, g2$grobs[[which(g2$layout$name == "panel")]], pp$t,
  15.     pp$l, pp$b, pp$l)

  16. # axis tweaks
  17. ia <- which(g2$layout$name == "axis-l")
  18. ga <- g2$grobs[[ia]]
  19. ax <- ga$children[[2]]
  20. ax$widths <- rev(ax$widths)
  21. ax$grobs <- rev(ax$grobs)
  22. ax$grobs[[1]]$x <- ax$grobs[[1]]$x - unit(1, "npc") + unit(0.15, "cm")
  23. g <- gtable_add_cols(g, g2$widths[g2$layout[ia, ]$l], length(g$widths) - 1)
  24. g <- gtable_add_grob(g, ax, pp$t, length(g$widths) - 1, pp$b)

  25. # draw it
  26. grid.draw(g)
复制代码
  1. x <- seq(1992, 2002, by = 2)

  2. d1 <- data.frame(x = x, y = rnorm(length(x)))
  3. xy <- expand.grid(x = x, y = x)
  4. d2 <- data.frame(x = xy$x, y = xy$y, z = jitter(xy$x + xy$y))

  5. d1$panel <- "a"
  6. d2$panel <- "b"
  7. d1$z <- d1$x

  8. d <- rbind(d1, d2)

  9. p <- ggplot(data = d, mapping = aes(x = x, y = y))
  10. p <- p + facet_grid(panel ~ ., scale = "free")
  11. p <- p + layer(data = d1,  geom = c( "line"), stat = "identity")
  12. p <- p + layer(data = d2, mapping = aes(colour = z, fill = z),
  13.     geom = "tile", stat = "identity")
  14. p
复制代码


二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

关键词:ggplot2 gplot plot GPL 双坐标 library

沙发
mathstu 在职认证  发表于 2013-4-30 18:41:37
很不错 很强大!谢谢楼主共享!

藤椅
chenyouliang 发表于 2013-4-30 19:36:29
很不错 很强大!谢谢楼主共享!
可怕的不是很多人比你更牛逼,而是牛逼的人比你更努力

板凳
xlyshuai 发表于 2015-4-8 11:16:13
请问,如将副坐标轴的标题也加进去?谢谢!

报纸
toalwhen 发表于 2016-8-16 09:31:24
xlyshuai 发表于 2015-4-8 11:16
请问,如将副坐标轴的标题也加进去?谢谢!
同问。求问已经解决这个问题了吗?

地板
alecwf 发表于 2018-11-15 22:31:30
收藏了,谢谢分享

7
yangming98 发表于 2018-11-15 22:35:38 来自手机
famousid 发表于 2013-4-25 23:27
好的好的好的好的

8
tianwk 发表于 2019-7-25 16:55:31
thanks for sharing

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
加好友,备注cda
拉您进交流群
GMT+8, 2025-12-30 05:06