knitr::opts_chunk$set(echo = TRUE)
library(tmap)
library(readxl)
library(grid)
library(dplyr)
library(sf)
library(ggplot2)
library(microbenchmark)

Large choroplth

# function to obtain Food Environment Atlas data (2014)
get_food_envir_data <- function() {
    dir <- tempdir()
    if (!file.exists(file.path(dir, "DataDownload.xls"))) {
        download.file("https://www.ers.usda.gov/webdocs/DataFiles/48731/February2014.xls?v=41688", destfile = file.path(dir, "DataDownload.xls"), mode = "wb")
    }
    res <- tryCatch({
        read_excel(file.path(dir, "DataDownload.xls"), sheet = "HEALTH")    
    }, error = function(e) {
        stop("The excel file cannot be read. Please open it, and remove all sheets except HEALTH. The location of the file is: ", normalizePath(file.path(dir, "DataDownload.xls")))
    })
    res[!duplicated(res$FIPS), ]
}

# function to obtain US county shape
get_US_county_2010_shape <- function() {
    dir <- tempdir()
    download.file("http://www2.census.gov/geo/tiger/GENZ2010/gz_2010_us_050_00_20m.zip", destfile = file.path(dir, "gz_2010_us_050_00_20m.zip"))
    unzip(file.path(dir, "gz_2010_us_050_00_20m.zip"), exdir = dir)
    US <- sf::read_sf(file.path(dir, "gz_2010_us_050_00_20m.shp"))
    levels(US$NAME) <- iconv(levels(US$NAME), from = "latin1", to = "utf8")
    US
}

# obtain Food Environment Atlas data
FEA <- get_food_envir_data()

# obtain US county shape
US <- get_US_county_2010_shape()

US$FIPS <- paste0(US$STATE, US$COUNTY)

# US <- left_join(US, FEA, by = c("FIPS", "FIPS")) # bug, lazy solution';
US$PCT_OBESE_ADULTS10 = FEA$PCT_OBESE_ADULTS10[match(US$FIPS, FEA$FIPS)]

US_cont <- US %>% 
    subset(!STATE %in% c("02", "15", "72"))
poly_sf = function() {
    plot(US_cont[, "PCT_OBESE_ADULTS10"])
}
poly_ggplot2 = function() {
    print(ggplot(data = US_cont, aes(fill = PCT_OBESE_ADULTS10)) + geom_sf())
}
poly_tmap = function() {
    print(tm_shape(US_cont) + tm_polygons("PCT_OBESE_ADULTS10"))    
}
poly_sf()
poly_ggplot2()
poly_tmap()
write2png = function(e) {
    tmp = tempfile(fileext = ".png")
    png(tmp, width = 2000, height = 2000)
    e
    dev.off()
}

autoplot(microbenchmark(list = alist(
sf = write2png(poly_sf()),
ggplot2 = write2png(poly_ggplot2()), 
tmap = write2png(poly_tmap())),
times = 3))

Large dot map

denuncia_v = read.csv("https://github.com/hbermeo/datos_espaciales/raw/master/denuncia_vial.csv", encoding = "UTF-8")

denuncias = st_as_sf(denuncia_v, coords = c("long", "lat"), crs = 4326)
dot_sf = function() {
    plot(denuncias[, "genero"])
}
dot_ggplot2 = function() {
    print(ggplot(data= denuncias, aes(color = genero)) + geom_sf())
}
dot_tmap = function() {
    print(tm_shape(denuncias) + tm_dots("genero", size = .1))
}
dot_sf()
dot_ggplot2()
dot_tmap()
autoplot(microbenchmark(list = alist(
sf = write2png(dot_sf()),
ggplot2 = write2png(dot_ggplot2()), 
tmap = write2png(dot_tmap())),
times = 3))


mtennekes/tmap documentation built on Aug. 31, 2022, 7:49 p.m.