简体   繁体   中英

ggplot: overlay two plots

Is it possible to overlay two plots with gridExtra (or other package)?

I want to rescale one plot and overlay it to a second one (specifying rescaling and coordinates)

require(ggplot2)
require(gridExtra)

df <- data.frame(value=rnorm(10), date=1:10)

p1 <- ggplot(data.frame(df), aes(value,date)) + geom_line()
p2 <- ggplot(data.frame(df), aes(value,date)) + geom_point()

to obtain something like this

在此输入图像描述

Look at gtable package in combination with gridExtra . You can specify size and coordinates of plot as you like.

require(gtable)

p1 <- ggplotGrob(p1)
p2 <- ggplotGrob(p2)

gt <- gtable(widths = unit(c(1, 2), "null"), heights = unit(c(.2, 1, 1), "null"))
gt <- gtable_add_grob(gt, p2, t = 1, b = 3, l = 1, r = 2)
gt <- gtable_add_grob(gt, p1, t = 2, l = 2)
grid.draw(gt)

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM