Mapes amb R

Lluís Ramon

Barcelona R user group 11 d’octubre de 2012

plot of chunk InicialitzarMesMapa

Objectius

Llibreria sp

DESCRIPTION: A package that provides classes and methods for spatial data. (…) Utility functions are provided, e.g. for plotting data as maps, spatial selection, as well as methods for retrieving coordinates, for subsetting, print, summary, etc

Classe S4

Orientat a objectes Tenim pensat parlar-ne a la propera reunió

Objectes

Per exemple

getClass("Spatial")
## Class "Spatial" [package "sp"]
## 
## Slots:
##                               
## Name:         bbox proj4string
## Class:      matrix         CRS
## 
## Known Subclasses: 
## Class "SpatialPoints", directly
## Class "SpatialGrid", directly
## Class "SpatialLines", directly
## Class "SpatialPolygons", directly
## Class "SpatialPointsDataFrame", by class "SpatialPoints", distance 2
## Class "SpatialPixels", by class "SpatialPoints", distance 2
## Class "SpatialGridDataFrame", by class "SpatialGrid", distance 2
## Class "SpatialLinesDataFrame", by class "SpatialLines", distance 2
## Class "SpatialPixelsDataFrame", by class "SpatialPoints", distance 3
## Class "SpatialPolygonsDataFrame", by class "SpatialPolygons", distance 2
getClass("SpatialPolygons")
## Class "SpatialPolygons" [package "sp"]
## 
## Slots:
##                                                       
## Name:     polygons   plotOrder        bbox proj4string
## Class:        list     integer      matrix         CRS
## 
## Extends: "Spatial"
## 
## Known Subclasses: "SpatialPolygonsDataFrame"
getClass("SpatialPolygonsDataFrame")
## Class "SpatialPolygonsDataFrame" [package "sp"]
## 
## Slots:
##                                                                   
## Name:         data    polygons   plotOrder        bbox proj4string
## Class:  data.frame        list     integer      matrix         CRS
## 
## Extends: 
## Class "SpatialPolygons", directly
## Class "Spatial", by class "SpatialPolygons", distance 2

Mètodes visualització

Exemple estructura objecte sp: Mapa del món

library(maptools)
data(wrld_simpl)
is(wrld_simpl)
## [1] "SpatialPolygonsDataFrame" "SpatialPolygons"         
## [3] "Spatial"
slotNames(wrld_simpl)
## [1] "data"        "polygons"    "plotOrder"   "bbox"        "proj4string"
str(wrld_simpl, max.level = 2)
## Formal class 'SpatialPolygonsDataFrame' [package "sp"] with 5 slots
##   ..@ data       :'data.frame':  246 obs. of  11 variables:
##   ..@ polygons   :List of 246
##   .. .. [list output truncated]
##   ..@ plotOrder  : int [1:246] 145 175 24 209 30 21 9 71 98 8 ...
##   ..@ bbox       : num [1:2, 1:2] -180 -90 180 90
##   .. ..- attr(*, "dimnames")=List of 2
##   ..@ proj4string:Formal class 'CRS' [package "sp"] with 1 slots
head(slot(wrld_simpl, "data"))
##     FIPS ISO2 ISO3 UN                NAME   AREA  POP2005 REGION SUBREGION
## ATG   AC   AG  ATG 28 Antigua and Barbuda     44    83039     19        29
## DZA   AG   DZ  DZA 12             Algeria 238174 32854159      2        15
## AZE   AJ   AZ  AZE 31          Azerbaijan   8260  8352021    142       145
## ALB   AL   AL  ALB  8             Albania   2740  3153731    150        39
## ARM   AM   AM  ARM 51             Armenia   2820  3017661    142       145
## AGO   AO   AO  AGO 24              Angola 124670 16095214      2        17
##         LON    LAT
## ATG -61.783  17.08
## DZA   2.632  28.16
## AZE  47.395  40.43
## ALB  20.068  41.14
## ARM  44.563  40.53
## AGO  17.544 -12.30
str(polygons(wrld_simpl)[202], max.level = 3)
## Formal class 'SpatialPolygons' [package "sp"] with 4 slots
##   ..@ polygons   :List of 1
##   .. ..$ :Formal class 'Polygons' [package "sp"] with 5 slots
##   ..@ plotOrder  : int 1
##   ..@ bbox       : num [1:2, 1:2] 25.7 35.9 44.8 42
##   .. ..- attr(*, "dimnames")=List of 2
##   ..@ proj4string:Formal class 'CRS' [package "sp"] with 1 slots
bbox(wrld_simpl)
##     min max
## r1 -180 180
## r2  -90  90
proj4string(wrld_simpl)
## [1] " +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs +towgs84=0,0,0"

Exemple de visualitzar un mapa del món

# Exemples per mostrar que amb el plot directament ja fa el mapa i que es
# poden fer servir els parametres habituals
plot(wrld_simpl)
plot of chunk plotMapesMon
plot(wrld_simpl, bg = "black", border = "white")
plot of chunk plotMapesMon
plot(wrld_simpl, bg = "black", col = "white")
plot of chunk plotMapesMon
plot(wrld_simpl, bg = "steelblue1", col = "wheat", border = "sienna4", lwd = 1.6)
plot of chunk plotMapesMon

Dades de deute per paisos 2011 i previsions

# Les dades les les he generat al fer el mapa de la presentació
str(deutePerPaisos)
FALSE 'data.frame': 172 obs. of  8 variables:
FALSE  $ NAME        : chr  "Albania" "Algeria" "Angola" "Antigua and Barbuda" ...
FALSE  $ 2011        : num  59.4 10.7 29.9 68.6 43.3 ...
FALSE  $ 2012        : num  59.2 10.7 24.7 66.6 41.5 ...
FALSE  $ 2013        : num  59.6 10.7 19.9 63.9 40.4 ...
FALSE  $ 2014        : num  60.6 10.7 16.3 58.5 39.5 ...
FALSE  $ 2015        : num  62 10.6 13.7 54.8 38 ...
FALSE  $ 2016        : num  63.6 10.4 12.2 49.4 37.3 ...
FALSE  $ colorInt2011: atomic  #FC8D59 #3288BD #99D594 #FC8D59 ...
FALSE   ..- attr(*, "palette")= chr  "#3288BD" "#99D594" "#E6F598" "#FEE08B" ...
FALSE   ..- attr(*, "table")= 'table' int [1:6(1d)] 29 28 29 28 29 29
FALSE   .. ..- attr(*, "dimnames")=List of 1
FALSE   .. .. ..$ : chr  "[0,22.43)" "[22.43,34.15)" "[34.15,42.93)" "[42.93,55.12)" ...
summary(deutePerPaisos)
FALSE      NAME                2011            2012            2013      
FALSE  Length:172         Min.   :  0.0   Min.   :  0.0   Min.   :  0.0  
FALSE  Class :character   1st Qu.: 27.6   1st Qu.: 27.9   1st Qu.: 27.8  
FALSE  Mode  :character   Median : 42.9   Median : 43.5   Median : 43.5  
FALSE                     Mean   : 49.5   Mean   : 49.7   Mean   : 49.5  
FALSE                     3rd Qu.: 63.1   3rd Qu.: 64.0   3rd Qu.: 62.9  
FALSE                     Max.   :233.1   Max.   :238.4   Max.   :242.9  
FALSE       2014            2015            2016       colorInt2011      
FALSE  Min.   :  0.0   Min.   :  0.0   Min.   :  0.0   Length:172        
FALSE  1st Qu.: 26.8   1st Qu.: 26.5   1st Qu.: 26.4   Class :character  
FALSE  Median : 43.3   Median : 41.8   Median : 41.2   Mode  :character  
FALSE  Mean   : 49.0   Mean   : 47.8   Mean   : 46.9                     
FALSE  3rd Qu.: 60.5   3rd Qu.: 60.6   3rd Qu.: 59.7                     
FALSE  Max.   :245.8   Max.   :249.9   Max.   :253.4

Llibreria classInt

DESCRIPTION: A package for choosing univariate class intervals for mapping or other graphics purposes

Funcions importants

library(classInt)

int <- classIntervals(deutePerPaisos$"2011", 6, style = "quantile")
int
## style: quantile
##     [0,22.43) [22.43,34.15) [34.15,42.93) [42.93,55.12) [55.12,76.18) 
##            29            28            29            28            29 
## [76.18,233.1] 
##            29

colorsPaleta = c("red", "blue", "yellow", "green", "brown", "orange")
plot(int, pal = colorsPaleta)
plot of chunk classInt

deutePerPaisos$colorInt2011 = findColours(int, colorsPaleta)

head(deutePerPaisos)
##                  NAME  2011  2012  2013  2014  2015  2016 colorInt2011
## 1             Albania 59.36 59.24 59.56 60.58 62.01 63.63      #A52A2A
## 2             Algeria 10.65 10.71 10.68 10.68 10.57 10.37      #FF0000
## 3              Angola 29.91 24.71 19.89 16.32 13.73 12.24      #0000FF
## 4 Antigua and Barbuda 68.63 66.58 63.90 58.54 54.80 49.36      #A52A2A
## 5           Argentina 43.35 41.47 40.38 39.49 38.02 37.31      #00FF00
## 6             Armenia 41.48 41.39 39.28 37.42 37.02 36.51      #FFFF00

Creuar i representar mapa



# L'ordre dels registres és important, si al fer la fusió es modifica, els
# mapes sortiran malament.

# Opció joint del package plyr ( la que vaig fer serir a la presentació)
library(plyr)
names(deutePerPaisos) = c("NAME", "2011", "2012", "2013", "2014", "2015", "2016", 
    "colorInt2011")  # Canviem el nom de country per NAME per fer la fusió de les dades amb el join
dadesFusionades = join(wrld_simpl@data, deutePerPaisos)
## Joining by: NAME

# Opció match i afegir la columna que volem indexOrdre =
# match(wrld_simpl@data$NAME, deutePerPaisos$NAME)
# wrld_simpl@data$colorInt2011 = deutePerPaisos[indexOrdre,
# 'colorInt2011']

head(dadesFusionades)
##   FIPS ISO2 ISO3 UN                NAME   AREA  POP2005 REGION SUBREGION
## 1   AC   AG  ATG 28 Antigua and Barbuda     44    83039     19        29
## 2   AG   DZ  DZA 12             Algeria 238174 32854159      2        15
## 3   AJ   AZ  AZE 31          Azerbaijan   8260  8352021    142       145
## 4   AL   AL  ALB  8             Albania   2740  3153731    150        39
## 5   AM   AM  ARM 51             Armenia   2820  3017661    142       145
## 6   AO   AO  AGO 24              Angola 124670 16095214      2        17
##       LON    LAT  2011   2012  2013  2014  2015  2016 colorInt2011
## 1 -61.783  17.08 68.63 66.578 63.90 58.54 54.80 49.36      #A52A2A
## 2   2.632  28.16 10.65 10.709 10.68 10.68 10.57 10.37      #FF0000
## 3  47.395  40.43 10.68  9.971  9.98 10.31 11.49 12.96      #FF0000
## 4  20.068  41.14 59.36 59.242 59.56 60.58 62.01 63.63      #A52A2A
## 5  44.563  40.53 41.48 41.390 39.28 37.42 37.02 36.51      #FFFF00
## 6  17.544 -12.30 29.91 24.715 19.89 16.32 13.73 12.24      #0000FF

wrld_simpl@data = dadesFusionades

plot(wrld_simpl, col = wrld_simpl@data$colorInt2011)
legend("bottomleft", legend = leglabs(round(int$brks, 2)), fill = colorsPaleta, 
    inset = c(0.03, 0.23), title = "In percentage of national GDP")
title(main = "Gross government debt 2011")
plot of chunk encreuamentSpDeute

# Hi ha paisos que no tenen color perquè p.ex. Mongolia o Libia No hi eren
# a la base de dades de deute per paisos, per tant no ha creuat i se li ha
# assignat un NA

Llibreria RColorBrewer

DESCRIPTION: The packages provides palettes for drawing nice maps shaded according to a variable

Funcions importants

library(RColorBrewer)
display.brewer.pal(6, "Reds")
plot of chunk RColorBrewer
display.brewer.all()
plot of chunk RColorBrewerAll

Millorem l’estètica del mapa

# Repetim tot el procés realitzat anteriorment amb la paleta nova de
# RColorBrewer
int <- classIntervals(deutePerPaisos$"2011", 6)
colorsPaleta <- brewer.pal(6, "Spectral")
plot(int, pal = colorsPaleta)
plot of chunk classIntervalBrewer
colorsPaleta = colorsPaleta[6:1]
deutePerPaisos$colorInt2011 = findColours(int, colorsPaleta)
names(deutePerPaisos) = c("NAME", "2011", "2012", "2013", "2014", "2015", "2016", 
    "colorInt2011")

data(wrld_simpl)  # Carreguem de nou les dades que l'anterior l'haviem modificat
dadesFusionades = join(wrld_simpl@data, deutePerPaisos)
## Joining by: NAME
wrld_simpl@data = dadesFusionades
plot(wrld_simpl, col = wrld_simpl@data$colorInt2011)
plot of chunk plotMapaMonArreglat

plot(wrld_simpl, col = wrld_simpl@data$colorInt2011, bg = "black")
plot of chunk plotMapaMonArreglat

# Solució afegir-li un color als NA
wrld_simpl@data$colorInt2011[is.na(wrld_simpl@data$colorInt2011) == TRUE] = "#808080"

plot(wrld_simpl, col = wrld_simpl@data$colorInt2011, bg = "black")


legend("bottomleft", legend = leglabs(round(int$brks, 2)), fill = colorsPaleta, 
    inset = c(0.03, 0.23), bg = "black", text.col = "white", box.col = "white", 
    title = "In percentage of national GDP")

title(main = "Gross government debt 2011")
plot of chunk plotMapaMonArreglat

Visualització pròpia de sp: spplot

# Canviem els noms que els camps 2011, 2012.. ens donen problemes
names(wrld_simpl) = make.names(names(wrld_simpl))

# Personalment no els he fet servir gaire però val la pena conèixer que
# existeixen
spplot(wrld_simpl, zcol = c("X2013", "X2014", "X2011", "X2012"), col.regions = colorRampPalette(c("blue", 
    "green", "orange", "red", "darkred"))(16))
plot of chunk spplot

Què és un Shapefile?

Format per l’intercanvi d’informació geogràfica (estàndard de facto)

Com importar-los a l’R? Llibreria maptools

library(maptools)
getinfo.shape("XXXX.shp")
readShapeSpatial("XXXX.shp")
readShapePoints("XXXX.shp")
readShapeLines("XXXX.shp")
readShapePoly("XXXX.shp")

# La llibreria maptools permet importar també altres tipus de fitxers
readAsciiGrid
readGPS
readSplus
Rgshhs
etc

Exemple de les línies i estacions de TMB

A Dades Obertes gencat hi ha diferents shapefiles disponibles

Xarxa de transports metropolitans de Barcelona (TMB)


# Dades de les estacions
getinfo.shape("~/Documents/R user Group/Intro Mapes amb R/Mapes amb R/TMB/TMB_EIX.shp")
## Shapefile type: PolyLine, (3), # of Shapes: 156
eixosTMB = readShapeLines("~/Documents/R user Group/Intro Mapes amb R/Mapes amb R/TMB/TMB_EIX.shp")
str(eixosTMB, max.level = 2)
## Formal class 'SpatialLinesDataFrame' [package "sp"] with 4 slots
##   ..@ data       :'data.frame':  156 obs. of  7 variables:
##   .. ..- attr(*, "data_types")= chr [1:7] "N" "C" "C" "C" ...
##   ..@ lines      :List of 156
##   .. .. [list output truncated]
##   ..@ bbox       : num [1:2, 1:2] 422146 4577261 436959 4590622
##   .. ..- attr(*, "dimnames")=List of 2
##   ..@ proj4string:Formal class 'CRS' [package "sp"] with 1 slots
head(slot(eixosTMB, "data"))
##   ID NOM_CAPA     MODALITAT LINIA
## 0 72      Eix METRO_LLEUGER   L11
## 1 73      Eix METRO_LLEUGER   L11
## 2 74      Eix METRO_LLEUGER   L11
## 3 75      Eix         METRO    L2
## 4 76      Eix         METRO    L2
## 5 77      Eix         METRO    L2
##                                  INICI_FINA TIPUS_VIA OBSERVACIO
## 0  Casa de l'Aigua-Torre Bar\xf3 | Vallbona  \xdanica       <NA>
## 1 Torre Bar\xf3 | Vallbona-Ciutat Meridiana  \xdanica       <NA>
## 2             Ciutat Meridiana-Can Cui\xe0s  \xdanica       <NA>
## 3                     Paral.lel-Sant Antoni     Doble       <NA>
## 4                   Sant Antoni-Universitat     Doble       <NA>
## 5               Passeig de Gr\xe0cia-Tetuan     Doble       <NA>
plot(eixosTMB)
plot of chunk importarDadesTMB
plot(eixosTMB, col = eixosTMB@data$LINIA)
plot of chunk importarDadesTMB

# Dades de les estacions
getinfo.shape("~/Documents/R user Group/Intro Mapes amb R/Mapes amb R/TMB/TMB_EST.shp")
## Shapefile type: MultiPoint, (8), # of Shapes: 684
estacionsTMB = readShapePoints("~/Documents/R user Group/Intro Mapes amb R/Mapes amb R/TMB/TMB_EST.shp")
str(estacionsTMB, max.level = 2)
## Formal class 'SpatialPointsDataFrame' [package "sp"] with 5 slots
##   ..@ data       :'data.frame':  684 obs. of  11 variables:
##   .. ..- attr(*, "data_types")= chr [1:11] "N" "C" "C" "C" ...
##   ..@ coords.nrs : num(0) 
##   ..@ coords     : num [1:684, 1:2] 429879 422302 423048 423056 423478 ...
##   .. ..- attr(*, "dimnames")=List of 2
##   ..@ bbox       : num [1:2, 1:2] 422302 4577356 437051 4590673
##   .. ..- attr(*, "dimnames")=List of 2
##   ..@ proj4string:Formal class 'CRS' [package "sp"] with 1 slots
head(slot(estacionsTMB, "data"))
##    ID NOM_CAPA MODALITAT LINIA         NOM_ESTACI ESTAT_PMR ZONIFICACI
## 0 248 Accessos     METRO    L3           Diagonal      <NA>       <NA>
## 1 249 Accessos     METRO    L5 Cornell\xe0 Centre      <NA>       <NA>
## 2 250 Accessos     METRO    L5            Gavarra      <NA>       <NA>
## 3 251 Accessos     METRO    L5            Gavarra      <NA>       <NA>
## 4 252 Accessos     METRO    L5      Sant Ildefons      <NA>       <NA>
## 5 253 Accessos     METRO    L5      Sant Ildefons      <NA>       <NA>
##   CORRESPOND SERVEIS OBSERVACIO GMRotation
## 0       <NA>    <NA>       <NA>          0
## 1       <NA>    <NA>       <NA>          0
## 2       <NA>    <NA>       <NA>          0
## 3       <NA>    <NA>       <NA>          0
## 4       <NA>    <NA>       <NA>          0
## 5       <NA>    <NA>       <NA>          0
# ESTAT_PMR: Defineix si l'accés a les estacions està adaptat per a
# persones de mobilitat reduïda o si està en estudi, projecte o obres
# d'adaptació.
plot(estacionsTMB, col = estacionsTMB@data$ESTAT_PMR, pch = 19)
plot of chunk importarDadesTMB

Combinar dos sp

# Es poden combinar diferentes dades espaials
plot(eixosTMB, col = eixosTMB@data$LINIA)
plot(estacionsTMB, col = estacionsTMB@data$ESTAT_PMR, pch = 19, add = TRUE, 
    cex = 0.5)
plot of chunk combinarSHP

Llibreria rgdal, canviant el sistema de coordenades

DESCRIPTION: Provides bindings to Frank Warmerdam’s Geospatial Data Abstraction Library (GDAL) (>= 1.6.0) and access to projection/transformation operations from the PROJ.4 library


proj4string(estacionsTMB) = CRS("+proj=utm +zone=31")
head(coordinates(estacionsTMB))
##   coords.x1 coords.x2
## 0    429879   4583289
## 1    422302   4579056
## 2    423048   4579106
## 3    423056   4579089
## 4    423478   4579708
## 5    423491   4579676

# Fer canvi de sistema de coordenades de UTM a longlat
require(rgdal)
## Loading required package: rgdal
## Geospatial Data Abstraction Library extensions to R successfully loaded
## Loaded GDAL runtime: GDAL 1.9.0, released 2011/12/29 Path to GDAL shared
## files:
## /Library/Frameworks/R.framework/Versions/2.15/Resources/library/rgdal/gdal
## Loaded PROJ.4 runtime: Rel. 4.8.0, 6 March 2012, [PJ_VERSION: 480] Path to
## PROJ.4 shared files:
## /Library/Frameworks/R.framework/Versions/2.15/Resources/library/rgdal/proj
estacionsTMB = spTransform(estacionsTMB, CRS("+proj=longlat"))
lon = coordinates(estacionsTMB)[, 1]
lat = coordinates(estacionsTMB)[, 2]
estacionsLonLat = cbind(estacionsTMB@data, lon, lat)
head(estacionsLonLat)
##    ID NOM_CAPA MODALITAT LINIA         NOM_ESTACI ESTAT_PMR ZONIFICACI
## 0 248 Accessos     METRO    L3           Diagonal      <NA>       <NA>
## 1 249 Accessos     METRO    L5 Cornell\xe0 Centre      <NA>       <NA>
## 2 250 Accessos     METRO    L5            Gavarra      <NA>       <NA>
## 3 251 Accessos     METRO    L5            Gavarra      <NA>       <NA>
## 4 252 Accessos     METRO    L5      Sant Ildefons      <NA>       <NA>
## 5 253 Accessos     METRO    L5      Sant Ildefons      <NA>       <NA>
##   CORRESPOND SERVEIS OBSERVACIO GMRotation   lon   lat
## 0       <NA>    <NA>       <NA>          0 2.161 41.40
## 1       <NA>    <NA>       <NA>          0 2.071 41.36
## 2       <NA>    <NA>       <NA>          0 2.080 41.36
## 3       <NA>    <NA>       <NA>          0 2.080 41.36
## 4       <NA>    <NA>       <NA>          0 2.085 41.37
## 5       <NA>    <NA>       <NA>          0 2.085 41.36

RGoogleMaps

DESCRIPTION: This package serves two purposes: (i) Provide a comfortable R interface to query the Google server for static maps, and (ii) Use the map as a background image to overlay plots within R. This requires proper coordinate scaling.

library(RgoogleMaps)
head(estacionsLonLat)
##      ID  NOM_CAPA MODALITAT LINIA         NOM_ESTACI ESTAT_PMR ZONIFICACI
## 108 354 Estacions     METRO    L2 Sagrada Fam\xedlia  Adaptada     Zona 1
## 109 355 Estacions     METRO    L2            Encants  Adaptada     Zona 1
## 110 356 Estacions     METRO    L2               Clot  Adaptada     Zona 1
## 111 357 Estacions     METRO    L2        Bac de Roda  Adaptada     Zona 1
## 112 358 Estacions     METRO    L2      Sant Mart\xed  Adaptada     Zona 1
## 113 359 Estacions     METRO    L2             La Pau  Adaptada     Zona 1
##             CORRESPOND SERVEIS OBSERVACIO GMRotation   lon   lat numEnll
## 108                 L5    <NA>       <NA>          0 2.176 41.41       1
## 109               <NA>    <NA>       <NA>          0 2.184 41.41       0
## 110 L1-R.1-R2-R.2N-R11    <NA>       <NA>          0 2.188 41.41       5
## 111               <NA>    <NA>       <NA>          0 2.197 41.42       0
## 112               <NA>    <NA>       <NA>          0 2.202 41.42       0
## 113                 L4    <NA>       <NA>          0 2.207 41.43       1
mapaEstacions = GetMap.bbox(estacionsLonLat$lon, estacionsLonLat$lat)
## [1] "http://maps.google.com/maps/api/staticmap?center=41.4080142045794,2.16901629518613&zoom=12&size=640x640&maptype=terrain&format=png32&sensor=true"
PlotOnStaticMap(mapaEstacions, estacionsLonLat$lat, estacionsLonLat$lon, pch = 19)
plot of chunk PlotOnStaticMap

library(scales)  # Llibreria de suport a ggplot2 per millorar escales i 'breaks'
PlotOnStaticMap(mapaEstacions, estacionsLonLat$lat, estacionsLonLat$lon, pch = 19, 
    cex = rescale(estacionsLonLat$numEnll, to = c(0.5, 2.5)))
plot of chunk PlotOnStaticMap
# Funcions útils si fas servir la funció GetMap, on has de definir el
# centre i el zoom del mapa que vols descarregar-te de google maps
estacionsBbox = qbbox(estacionsLonLat$lat, estacionsLonLat$lon)
estacionsBbox
## $latR
## [1] 41.35 41.46
## 
## $lonR
## [1] 2.071 2.246
## 
MaxZoom(range(estacionsBbox$latR), range(estacionsBbox$lonR))
## MaxZoom.lat MaxZoom.lon 
##          12          12

Llibreria ggmap

ggplot2 + RGoogleMaps

Funcions pròpies molt interessants

library(ggmap)

geocode("Central UB, Barcelona")
##     lon   lat
## 1 2.164 41.39
revgeocode(c(2.164033, 41.38655), output = "address")
## [1] "Gran Via de les Corts Catalanes, 585, University of Barcelona, 08007 Barcelona, Catalonia, Spain"
mapdist("Tarragona", "Barcelona")
##        from        to     m km miles seconds minutes hours
## 1 Tarragona Barcelona 96998 97 60.27    4184   69.73 1.162
route("Central UB, Barcelona", "Plaça Catalunya, Barcelona")
##     m    km   miles seconds minutes    hours startLon startLat endLon
## 1 269 0.269 0.16716      39  0.6500 0.010833    2.164    41.39  2.162
## 2 285 0.285 0.17710     159  2.6500 0.044167    2.162    41.38  2.164
## 3  45 0.045 0.02796      17  0.2833 0.004722    2.164    41.39  2.165
## 4 462 0.462 0.28709      69  1.1500 0.019167    2.165    41.39  2.170
## 5  91 0.091 0.05655      20  0.3333 0.005556    2.170    41.39  2.170
##   endLat leg
## 1  41.38   1
## 2  41.39   2
## 3  41.39   3
## 4  41.39   4
## 5  41.39   5

Diferent origen de mapes


BarcelonaMap <- qmap("barcelona", zoom = 14)
BarcelonaMap
plot of chunk qmap

BarcelonaMap <- qmap("barcelona", zoom = 14, source = "osm")
BarcelonaMap
plot of chunk qmap

BarcelonaMap <- qmap("barcelona", zoom = 12, source = "stamen", maptype = "toner")
BarcelonaMap
plot of chunk qmap

BarcelonaMap <- qmap("barcelona", zoom = 12, source = "stamen", maptype = "watercolor")
BarcelonaMap
plot of chunk qmap

Exemple de ggmap amb les nostres dades


BarcelonaMap <- qmap("barcelona", zoom = 13)

BarcelonaMap + geom_point(aes(x = lon, y = lat, colour = numEnll, size = numEnll), 
    data = estacionsLonLat)
## Warning: Removed 53 rows containing missing values (geom_point).
plot of chunk ggmapExample

BarcelonaMap + stat_density2d(aes(x = lon, y = lat, fill = ..level..), data = estacionsLonLat, 
    geom = c("point", "polygon"))
## Warning: Removed 53 rows containing non-finite values (stat_density2d).
plot of chunk ggmapExample

Llibreria googleVis (opcional)


library(googleVis)
GdeutePaisos = gvisGeoChart(wrld_simpl@data, locationvar = "NAME", colorvar = "X2011", 
    options = list(width = 800, height = 500))
print(GdeutePaisos)
GeoChartIDa0c53f77991a
Data: wrld_simpl@data • Chart ID: GeoChartIDa0c53f77991a
R version 2.15.1 (2012-06-22) • googleVis-0.2.17Google Terms of UseData Policy

Més informació

Com he fet la presentació? RStudio, knitr, pandoc i slidy

El text i el codi d’aquesta presentació és reproduible. La he fet amb markdown i el package knitr, que a l’RStudio versió 0.96 està tot integrat en la extensió Rmd. Directament he generat un fitxer en markdown md.

Per passar del codi html a presentació html he utilitzat pandoc.Slidy és una de les opcions per generar presentacions en html que pandoc

Codi Pandoc generar presentació pandoc -s -S -t slidy –mathjax mapesAmbR.md -o presentacioMapes.html

Amb la següent sessió

sessionInfo()
## R version 2.15.1 (2012-06-22)
## Platform: x86_64-apple-darwin9.8.0/x86_64 (64-bit)
## 
## locale:
## [1] C/en_US.UTF-8/C/C/C/C
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] googleVis_0.2.17   RJSONIO_1.0-0      mapproj_1.1-8.3   
##  [4] maps_2.2-6         scales_0.2.2       stringr_0.6       
##  [7] rgdal_0.7-19       plyr_1.7.1         RColorBrewer_1.0-5
## [10] classInt_0.1-18    e1071_1.6          class_7.3-4       
## [13] XML_3.95-0.1       ggmap_2.2          ggplot2_0.9.2.1   
## [16] RgoogleMaps_1.2.0  png_0.1-4          maptools_0.8-16   
## [19] lattice_0.20-6     sp_1.0-0           foreign_0.8-50    
## [22] knitr_0.8.5       
## 
## loaded via a namespace (and not attached):
##  [1] MASS_7.3-19      colorspace_1.1-1 dichromat_1.2-4  digest_0.5.2    
##  [5] evaluate_0.4.2   formatR_0.6      grid_2.15.1      gtable_0.1.1    
##  [9] labeling_0.1     memoise_0.1      munsell_0.3      proto_0.3-9.2   
## [13] reshape2_1.2.1   rjson_0.2.10     tools_2.15.1