0

I need to generate different maps using tmap. To create a continous colorbar I use style = "cont" together with defined breaks (breaks = seq(0, 100, 25))).

This works well if my data shows some variation (see map 1 below). However, I also have data for which there is no variation across the individual polygons (see map 2). Nevertheless, to allow for direct comparison I want to have the colorbar plotted for map 1 (full range between 0 and 100) also for map 2.

So far I found no solutions to fix that problem. Any ideas?

library(tidyverse)
library(tmap)
library(sf)
library(urbnmapr)

makeMap <- function(data){
  tm_shape(data) +
  tm_fill("par",
          palette = "RdYlGn",
          style = "cont",
          breaks = seq(0, 100, 25)) +
  tm_layout(legend.text.size = 1.5,
            legend.bg.color = "white",
            legend.bg.alpha = .8) +
  tm_borders(lwd = 1, col = "black")
}

# map 1
states_sf1 <- get_urbn_map("states", sf = TRUE) %>%  
  as.tibble() %>% 
  mutate(par = runif(51, 0 ,100)) %>% 
  st_as_sf() 

makeMap(states_sf1)

# map 2
states_sf2 <- get_urbn_map("states", sf = TRUE) %>%  
  as.tibble() %>% 
  mutate(par = 10) %>% 
  st_as_sf() 

makeMap(states_sf2)

Map 1

enter image description here

Map 2

enter image description here

mgrund
  • 1,415
  • 8
  • 10

1 Answers1

1

I didn't manage to find a solution with tmap, see here an alternative using ggplot2. The key aspect is to set limits on scale_fill_gradientn:

library(tidyverse)
library(sf)
#> Linking to GEOS 3.9.0, GDAL 3.2.1, PROJ 7.2.1
library(urbnmapr)

makeMap <- function(data){
  ggplot(data) +
    geom_sf(aes(fill=par)) +
    scale_fill_gradientn(colours = hcl.colors(5,"RdYlGn"), breaks = seq(0, 100, 25),
                         limits=c(0,100)) +
    guides(fill = guide_colorbar(reverse = TRUE))+
    theme_void()
}

# map 1
states_sf1 <- get_urbn_map("states", sf = TRUE) %>%  
  as.tibble() %>% 
  mutate(par = runif(51, 0 ,100)) %>% 
  st_as_sf() 
#> Warning: `as.tibble()` was deprecated in tibble 2.0.0.
#> Please use `as_tibble()` instead.
#> The signature and semantics have changed, see `?as_tibble`.

makeMap(states_sf1)

# map 2
states_sf2 <- get_urbn_map("states", sf = TRUE) %>%  
  as.tibble() %>% 
  mutate(par = 25) %>% 
  st_as_sf() 

makeMap(states_sf2)

Created on 2021-06-18 by the reprex package (v2.0.0)

dieghernan
  • 2,690
  • 8
  • 16
  • Thanks a lot for your solution, good to know that it is at least possible using ggplot However, it would be great to know if it's also possible using tmap or if I should start a new issue on GitHub to ask for such feature. I guess It would be no big deal to add it. – mgrund Jun 18 '21 at 14:11
  • The problem was fixed in [tmap](https://github.com/mtennekes/tmap/commit/4bb0f0024675492abf9c641588d98c40eab3614a). – mgrund Aug 20 '21 at 11:36