0

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

4
  • Not sure if this is possible when using "view" mode alone. There exists tmapProxy to update the map (more specifically, to add and remove layers) when using tmap in Shiny via renderTmap. Depends on in which context you want to use your interactive map.
    – mgrund
    Commented Apr 29, 2022 at 6:35
  • The goal is to have an online map, exactly like this: vincentchangeon.shinyapps.io/testtest but with the option to select the column of my dataframe i want to plot Commented Apr 29, 2022 at 11:06
  • Then renderTmap allows to do what you want. I suggest to play around with the example given in the documentation using tmapProxy and tm_remove_layer.
    – mgrund
    Commented Apr 29, 2022 at 14:10
  • 1
    yep, it did work, thank you man I wouldn't have find without you ! Commented Apr 29, 2022 at 15:00

1 Answer 1

0

Here is an alternative solution that allows you to create an interactive choropleth using tmap and leaflet programatically with as many layers as you want.

I am unable to download the data at the link provided, so I use an example dataset from the spData package.

library(tmap)
library(leaflet)
library(sf)
library(tidyverse)
library(spData)

#Set to interactive mode:
tmap_mode(mode = "view")

#Get data from spData package:
nz <- nz

#Create a function that allows you to make as many layers as you want:
#' create_tm_;ayer
#'
#' @param data - an sf dataframe
#' @param column - a string that is a column name in data
#'
#' @return - a tmap map

create_tm_layer <- function(data, column) {
  tm_shape(data,
           name = column) +
    tm_fill(col = column)
  
}

#Iterate over function with as many column names as you want
tmap_mode(mode="view")

columns <- c("Median_income", "Sex_ratio", "Population")

# This configures Population to be the variable that appears at first
variables_to_start_hidden <- columns[columns != "Population"]

results <- map(create_tm_layer, data = nz, .x = columns)

tmap_results <- Reduce(`+`, results)

tmap_leaflet_results <- tmap_leaflet(tmap_results) %>%
  hideGroup(variables_to_start_hidden)

Not the answer you're looking for? Browse other questions tagged or ask your own question.