Viewport example

Simple example on use of grid and viewports.

library(data.table)
library(ggplot2)
library(grid)

d <- data.table(
  x1 = rnorm(250, 0, 1),
  x2 = sample(1:3, size = 250, replace = T,
              prob = c(0.5, 0.2, 0.3))
)
d[, mu := 0.3 + 0.6 * x1 - 0.2 * (x2 == 2) + 0.1 * (x2 == 3)]
d[, y := rnorm(.N, mu, 2)]
p1 <- ggplot(d, aes(x = x1, y = y)) +
  geom_point()
plot(p1)

p2 <- ggplot(d, aes(x = x2)) +
  geom_histogram()
plot(p2)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Use grid and viewports to arrange the plots in one graphic.

pg1 <- ggplotGrob(p1)
pg2 <- ggplotGrob(p2)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
grid::grid.newpage()
vp <- viewport(x = 0.0, y = 0.1, 
               width = 0.4, height = 0.3,
               just = c("left", "bottom"))
pushViewport(vp)
grid.draw(pg1)
popViewport()
  
vp <- viewport(x = 0.5, y = 0.5, 
               width = 0.5, height = 1,
               just = c("left", "bottom"))
pushViewport(vp)
grid.draw(pg2)
popViewport()