Skip to content

Instantly share code, notes, and snippets.

@dfbarrero
Created November 22, 2017 18:23
Show Gist options
  • Select an option

  • Save dfbarrero/c7d20aaee5e5073c1fa9a41d0e159160 to your computer and use it in GitHub Desktop.

Select an option

Save dfbarrero/c7d20aaee5e5073c1fa9a41d0e159160 to your computer and use it in GitHub Desktop.
R script that uses Lattice to plot a Choropleth map.
#!/usr/bin/Rscript --vanilla
library(sp)
#library(RColorBrewer)
colorPalette <- colorRampPalette(c("white", "orange"))(32)
spain <- readRDS("ESP_adm1.rds")
# Datos de Informe Anual del Sector TIC y de los Contenidos en España 2016. ONTSI
data = read.table(text="
'Comunidad' 'density' 'population'
'Andalucía' 96 8409657
'Aragón' 28 1317076
'Cantabria' 109 581477
'Castilla-La Mancha' 26 2040379
'Castilla y León' 26 2435797
'Cataluña' 232 7441176
'Ceuta y Melilla' 0 170000
'Comunidad de Madrid' 807 6475872
'Comunidad Foral de Navarra' 62 640502
'Comunidad Valenciana' 212 4934993
'Extremadura' 26 1077715
'Galicia' 92 2710607
'Islas Baleares' 231 1150839
'Islas Canarias' 289 2154905
'La Rioja' 62 312647
'País Vasco' 300 2167707
'Principado de Asturias' 98 1034449
'Región de Murcia' 130 1472949", header=TRUE)
spain$density = as.numeric(data$density)
spain$population = as.numeric(data$population)
# Change these parameters
scale.parameter = 0.65 # scaling paramter. less than 1 is zooming in, more than 1 zooming out.
xshift = 4.5 # Shift to right in map units.
yshift = 4 # Shift to left in map units.
original.bbox = spain@bbox # Pass bbox of your Spatial* Object.
# Just copy-paste the following
edges = original.bbox
edges[1, ] <- (edges[1, ] - mean(edges[1, ])) * scale.parameter + mean(edges[1,]) + xshift
edges[2, ] <- (edges[2, ] - mean(edges[2, ])) * scale.parameter + mean(edges[2,]) + yshift
###
spplot(spain, "density", col.regions = colorPalette, col = "black",
xlim = edges[1, ], ylim = edges[2, ],
main="Densidad de población por comunidad autónoma")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment