Jana
Jana

Reputation: 33

Combine tmap and ggplot

I am trying to combine test1, a map made with tmap, with test2, a plot made with ggplot2, using cowplot::plot_grid.

library(ggplot2)
library(tmap)
library(cowplot)
library(ggplotify)

test2 <-ggplot(iris, aes(Sepal.Length, Sepal.Width, color = Species)) + geom_point()

data("World")

test1 <- tm_shape(World) + tm_polygons("HPI")

plot_grid(test1,test2)

tmap doesn't seem to be compatible with cowplot:

"In as_grob.default(plot) : Cannot convert object of class tmap into a grob"

same problem when using

tmap::tmap_arrange(test1,test2)

"Error in tmap_arrange(test1, test2) : Not all arguments are tmap objects "

I also tried to convert the tmap using functions like "as.grob" from ggplotify,

test3 <- as.grob(test1)

but no luck "Error in UseMethod("as.grob") : no applicable method for 'as.grob' applied to an object of class "tmap" "

Any suggestions?

Thanks!

Upvotes: 3

Views: 2384

Answers (1)

Martijn Tennekes
Martijn Tennekes

Reputation: 2051

Yes, I've recently added tmap_grob which does the job.

library(ggplot2)
library(tmap)
library(cowplot)
library(ggplotify)

test2 <-ggplot(iris, aes(Sepal.Length, Sepal.Width, color = Species)) + geom_point()

data("World")

tm <- tm_shape(World) + tm_polygons("HPI")
test1 <- tmap_grob(tm)

plot_grid(test1,test2)

Upvotes: 6

Related Questions