r-tmap / tmap-book

A book on elegant and informative maps with the tmap package
https://r-tmap.github.io
Other
33 stars 5 forks source link

Question: how to use grob shapes? #14

Open Nowosad opened 4 years ago

Nowosad commented 4 years ago

@mtennekes can you help me here. I have seen the examples (they look great BTW), but I have also tried to create my own cases and failed. You can see two of them below.

library(tmap)
library(grid)
library(ggplotify)
library(ggplot2)
data("metro", package = "tmap")

set.seed(222)
metro2 = metro[sample(1:nrow(metro), 30), ]
set.seed(231)
metro2$group = as.character(sample(1:3, size = nrow(metro2), replace = TRUE))

p1 = as.grob(~barplot(1:10))
p2 = as.grob(expression(plot(rnorm(10))))
p3 = as.grob(function() plot(sin))
p4 = ggplotGrob(ggplot(data.frame(x = 1:10, y = 1:10), aes(x, y)) + geom_point())

# what is wrong here?
tm_shape(metro2) +
  tm_symbols(shape = "group",
             shapes = list(p4, p4, p4)) 
#> Linking to GEOS 3.8.1, GDAL 3.0.4, PROJ 6.3.2

# is anything like this is even possible?
tm_shape(metro2) +
  tm_symbols(shape = "group",
             shapes = list(p1, p2, p3)) 

Created on 2020-11-09 by the reprex package (v0.3.0)

mtennekes commented 4 years ago

Use theme_ps() to get rid of ggplot2 margins etc.:

p4 = ggplotGrob(ggplot(data.frame(x = 1:10, y = 1:10), aes(x, y)) + geom_point() + theme_ps())

image

mtennekes commented 4 years ago

Note to self: theme_void()

Nowosad commented 4 years ago

Hi @mtennekes, there is still one question left - would it be possible to use any grob objects as shapes?

Also, the previous example does not scale well (ggplots have large points as shapes) - would it be possible to adjust scale somehow?

library(tmap)
library(grid)
library(ggplotify)
library(ggplot2)
data("metro", package = "tmap")

set.seed(222)
metro2 = metro[sample(1:nrow(metro), 30), ]
set.seed(231)
metro2$group = as.character(sample(1:3, size = nrow(metro2), replace = TRUE))

p1 = as.grob(~barplot(1:10))
p2 = as.grob(expression(plot(rnorm(10), yaxt = "n", xaxt = "n", ann = FALSE, bty = "n")))
p3 = as.grob(function() plot(sin, yaxt = "n", xaxt = "n", ann = FALSE, bty = "n"))

tm_shape(metro2) +
  tm_symbols(shape = "group",
             shapes = list(p1, p2, p3)) 
#> Linking to GEOS 3.8.1, GDAL 3.0.4, PROJ 6.3.2

Created on 2020-11-30 by the reprex package (v0.3.0)