CptNemo
CptNemo

Reputation: 6755

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

enter image description here

Upvotes: 4

Views: 2641

Answers (1)

inscaven
inscaven

Reputation: 2584

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)

enter image description here

Upvotes: 4

Related Questions