Ggplot: overlay two plots

Is it possible to overlay two plots using gridExtra (or another package)?

I want to rescale one plot and overlay it on the second one (specifying scaling 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 get something like this

enter image description here

+3


source to share


1 answer


Look at the package gtable

in conjunction with gridExtra

. You can specify the size and coordinates of the 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)

      



enter image description here

+2


source







All Articles