JerryTheForester
JerryTheForester

Reputation: 476

Combine plots of different classes in R

I am working with plots of different classes in r, namely tmap (main plots) and ggplot (represent minor information).

library(raster)
library(tmap)
library(RStoolbox)
library(gridExtra)
library(ggplot2)

data("World")
r1 <- raster(ncol=2, nrow=2)
values(r1) <- c(1.5, -0.5, 0.5, -1.5)

r2 <- raster(ncol=2, nrow=2)
values(r2) <- c(1, 1, 0.5, -1.5)

# Then I create two tmap objects and two ggplot objects
tm1 <- tm_shape(World) + tm_polygons()  
tm2 <- tm_shape(World) + tm_polygons()

gg1 <- ggR(r1,  coord_equal = F, geom_raster = 1) + theme(legend.position = "none", axis.title = element_blank(), axis.text = element_text(size = 3.5))
gg2 <- ggR(r2,  coord_equal = F, geom_raster = 1) + theme(legend.position = "none", axis.title = element_blank(), axis.text = element_text(size = 3.5))

# Save each separately
# 1 tmap
current.mode <- tmap_mode("plot")
tmap_plot <- tmap_arrange(tm1, tm2, ncol = 1, nrow = 2)
tmap_save(tmap_plot, "tmap_plot.png", height = 8, width = 6)

# 2 ggplot
g <- arrangeGrob(gg1, gg2)
ggsave(file = "ggplot.png", g, height = 1.75, width = 1.75)

Currently, I save each class separately and combine them by using manual editing tools. I am looking for a solution, how to automate that process already in r. I am also open for suggestions, how to do it in other programming languages, just that it automates the process. Switching to different classes is not an option in my case.

enter image description here

Upvotes: 0

Views: 242

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 174546

You can draw the ggplots directly over the tmaps using a grid::viewport.

First, load grid and set the desired viewport location and dimensions:

library(grid)

subplot_vp <- viewport(x = 0.15, 
                       y = 0.35, 
                       width = unit(0.25, "npc"), 
                       height = unit(0.25, "npc"),
                       name = "inset")

Now you can do

tm1
grid.draw(grobTree(ggplotGrob(gg1), vp = subplot_vp))

enter image description here

and

tm2
grid.draw(grobTree(ggplotGrob(gg2), vp = subplot_vp))

enter image description here

Upvotes: 1

Related Questions