'Multiple layers on TMAP

I have a dataframe looking like this:

dataframe

Id is the zip code and the columns go from 2015 to 2019.

Link to download the database (with the .shp file needed to execute this program)




library(dplyr)
library(sf) # pour gérer les fichiers shapefile
library(ggplot2)
library(tmap) # pour créer une carte 
library(leaflet)
library(stringi) # pour le problème d'encodage du fichier shapefile
library(maptools)
library(mapview) # permet une carte dynamique

base= read.csv("../bddlongsubstance.csv", stringsAsFactors = FALSE, encoding = "UTF-8", sep= ",", dec= ".")
base= data.frame(base)
base$code_postal_acheteur= as.factor(base$code_postal_acheteur)
names(base)[1]= "ID"


codes_postaux= st_read(dsn = "../codes_postaux_V5/codes_postaux_region.shp", 
                       layer = "codes_postaux_region",
                       quiet = TRUE) %>%
  select(ID, LIB, DEP)

codes_postaux$LIB= stri_encode(codes_postaux$LIB, from= "ISO-8859-1", to= "utf8")

fusion= codes_postaux %>% 
  left_join(base[1:17], by= "ID") %>%
  st_transform(2154)
summary(fusion)


tmap_mode(mode= "view")
autre_2015= 
  tm_basemap("CartoDB.Voyager")+ tm_shape(shp= fusion)+
  tm_fill(col= "Autre_quantite.totale.2015", palette= "YlOrBr", id= "ID",
          textNA = "Valeur manquante", style = "quantile", n= 6, title= "Quantité totale : <br> Catégorie AUTRE",
          popup.vars = c("Ville"= "LIB", "Quantité"= "Autre_quantite.totale.2015"))+
  tm_borders("black", lwd= 0.3, alpha= 0.6)+
  tm_layout(title = "Quantité de substances phytopharmaceutiques achetées en 2015 (en kilogrammes)", title.position = c("center", "bottom"), legend.bg.color = "white", legend.bg.alpha = 0.4)+
  tm_scale_bar(position = c("left", "bottom"))+
  tm_view(view.legend.position = c("right", "bottom"))

tmap_mode(mode= "view")
toxique_2015=
  tm_basemap("CartoDB.Voyager")+ tm_shape(shp= fusion)+
  tm_fill(col= "Toxique_quantite.totale.2015", palette= "YlOrBr", id= "ID", 
          textNA = "Valeur manquante", style = "quantile", n= 6, title= "Quantité totale : <br> Catégorie TOXIQUE",
          popup.vars = c("Ville"= "LIB", "Quantité"= "Toxique_quantite.totale.2015"))+
  tm_borders("black", lwd= 0.3, alpha= 0.6)+
  tm_layout(title = "Quantité de substances phytopharmaceutiques achetées en 2015 (en kilogrammes)", title.position = c("center", "bottom"), legend.bg.color = "white", legend.bg.alpha = 0.4)+
  tm_scale_bar(position = c("left", "bottom"))+
  tm_view(view.legend.position = c("right", "bottom"))


with this code I can only generate one map simultaneously that looks like this:

picture of the map

but ideally, I would like a system with multiple layers and where I can select whatever column from the dataframe i want to display but I really can't find how to.

Thanks



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source