Search code examples
rr-gridtmap

Align lattice and tmap outputs using viewports


I am trying to align several panels (2 maps) and a lattice output from the package openair, with some explanatory text using grid:

enter image description here

However, I would like the left margin of the lattice output to be aligned with the left edge of the map on the top left, and the text aligned to the left margin of the topright map.

ideally, I would like to get this:

enter image description here

The code I am using is this:

library(tmap)
library(tmaptools)
library(openair)
library(grid)
library(gridExtra)


london_map <- qtm(read_osm("London"))
london_terrain <- qtm(read_osm("London", type = "stamen-terrain"))

pp_plot <- polarPlot(mydata, type="season")
top.vp <- 
  viewport(layout=grid.layout(3, 11,
                              heights=unit(c(0.5, 3.5 ,4), "inches"),
                              widths=unit(c(1,1,1,1,1,1,1,1,1,1), "inches")))


png(filename = "test.png", width = 11, height = 8, units ="in", res=72)

grid.newpage()
pushViewport(top.vp)
print(london_map, vp = viewport(layout.pos.row = 2, layout.pos.col=1:5, just="left"))
print(london_terrain, vp = viewport(layout.pos.row = 2, layout.pos.col=6:11, just="left"))

pushViewport(viewport(layout.pos.row = 3, layout.pos.col=1:7))
plot(pp_plot$plot, newpage=FALSE)
popViewport()     
pushViewport(viewport(layout.pos.row = 3, layout.pos.col=8))
grid.text("Notes: \n1. quo durius te exerces, eo facilius certabis\n2. Ursis fidimus\n3. audaces fortuna juvat \n", just=0)

dev.off()

I have tired working with the just arguments, but to no avail.


Solution

  • OK based on the above, this achieved what I needed. I needed to use negative positions:

    png(filename = "test.png", width = 11, height = 8, units ="in", res=72)
    
    grid.newpage()
    pushViewport(top.vp)
    print(london_map, vp = viewport(layout.pos.row = 2, layout.pos.col=1:5, just=c("left","top")))
    print(london_terrain, vp = viewport(layout.pos.row = 2, layout.pos.col=6:11, just="left"))
    
    pushViewport(viewport(layout.pos.row = 3, layout.pos.col=1:7))
    plot(pp_plot$plot, newpage=FALSE, position=c(-0.18,0,0.82,1))
    popViewport()     
    pushViewport(viewport(layout.pos.row = 3, layout.pos.col=6))
    grid.text("Notes: \n1. quo durius te exerces, eo facilius certabis\n2. Ursis fidimus\n3. audaces fortuna juvat \n", 
              x = 0.85, just = "left")
    
    dev.off()