forked from maritrinez/Rmaps_medialab
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.Rmd
582 lines (435 loc) · 15.2 KB
/
index.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
---
title : Maps with R
subtitle : Workshop
author : Beatriz Martínez
job :
framework : io2012 # {io2012, html5slides, shower, dzslides, ...}
highlighter : highlight.js # {highlight.js, prettify, highlight}
hitheme : tomorrow #
widgets : [interactive] # {mathjax, quiz, bootstrap}
mode : selfcontained # {standalone, draft}
knit : slidify::knit2slides
---
## CONTENT
> 1. Read shapefiles into R... (datos geográficos)
> 2. ...and plot some meaningful data. (datos asociados)
> 3. Plot a map on a streetmap (ggplot + ggmap) (referencia)
> 4. Remove the background street map.
> 5. googleVis
---
## 1. Read shapefiles into R... (datos geográficos)
```{r options, include=FALSE}
opts_chunk$set(warning = FALSE, error=FALSE, message=FALSE, tidy=TRUE)
```
#### GET READY
```{r setwd}
wd <- "/Users/martinez/Dropbox/R"
setwd(paste(wd, "/R_maps_workshop_slidify", sep = ""))
# Download the source from http://www.stats.ox.ac.uk/pub/RWin/bin/macosx/mavericks/contrib/3.1/
# install.packages("packages/rgdal_0.8-16.tgz", repos = NULL)
# install.packages("packages/rgeos_0.3-4.tgz", repos = NULL)
library(rgeos)
library(rgdal)
library(sp)
library(maptools)
```
---
## 1. Read shapefiles into R... (datos geográficos)
#### POINT SHAPEFILES: the parks
> Load a Shapefile into R (downladed from [madrid.org](http://www.madrid.org
/nomecalles/DescargaBDTCorte.icm))
```{r load_parks, tidy.opts=list(blank=FALSE, width.cutoff=20), }
# get info
getinfo.shape("Shapefiles/MAD_CM_parques_jardines/parques.shp")
# set projection
ED50<-CRS(paste("+proj=utm +zone=30 +ellps=intl +units=m +no_defs"))
# http://cicero.azavea.com/docs/epsg_codes.html equal to 'ED50(ED77)
# / UTM zone 38N' but Marid is in the UTM zone 30
# read the shapefile
parquesMadrid <- readShapePoints("Shapefiles/MAD_CM_parques_jardines/parques.shp", proj4string = ED50)
```
---
## 1. Read shapefiles into R... (datos geográficos)
##### Shapefiles structure
```{r parks_structure}
str(parquesMadrid, max.level = 2)
parquesMadrid@bbox
````
---
## 1. Read shapefiles into R... (datos geográficos)
##### Shapefiles structure
```{r parks_structure_2}
head(parquesMadrid@data)
```
---
## 1. Read shapefiles into R... (datos geográficos)
##### Simple plot
```{r simple_plot}
# which objtect plot, and by which variable set the color.
plot(parquesMadrid, col = parquesMadrid$MUNICIPIO)
```
---
## 1. Read shapefiles into R... (datos geográficos)
##### Simple plot
```{r simple_plot_2}
# plot a subset
parquesMadrid <- parquesMadrid[parquesMadrid$MUNICIPIO == "Madrid", ]
plot(parquesMadrid, col = parquesMadrid$MUNICIPIO)
```
---
## 1. Read shapefiles into R... (datos geográficos)
##### Simple plot
```{r simple_plot_3}
# add format attributes
plot(parquesMadrid, pch = 20, cex = 2, col = "springgreen3")
```
---
## 1. Read shapefiles into R... (datos geográficos)
#### POLYGON SHAPEFILES: the neighborhoods
```{r load_barrios}
getinfo.shape("Shapefiles/MAD_barrios_madrid/barrios_madrid.shp")
barriosMadrid <- readShapePoly("Shapefiles/MAD_barrios_madrid/barrios_madrid.shp", proj4string = ED50)
class(barriosMadrid)
````
---
## 1. Read shapefiles into R... (datos geográficos)
#### POLYGON SHAPEFILES: the neighborhoods
```{r barrios_structure}
str(barriosMadrid, max.level = 2)
barriosMadrid@bbox
head(barriosMadrid@data)
```
---
## 1. Read shapefiles into R... (datos geográficos)
#### POLYGON SHAPEFILES: the neighborhoods
```{r simple_plot_4}
plot(barriosMadrid)
plot(parquesMadrid, pch = 20, cex = 2, col = "springgreen3", add = TRUE)
```
---
## 2. ... and plot some meaningful data (atributos asociados)
Merge the meaningful data (e.g. neigborhoods density) with the SpatialPolygonDataFrame @data slot.
1. read the neigborhoods density.
2. get ready to merge both data frames
3. merge them
4. and plot!
---
## 2. ... and plot some meaningful data (atributos asociados)
#### Read the neigborhoods density.
downladed from [munimadrid](http://www-2.munimadrid.es/CSE6/control/seleccionDatos?numSerie=14010100010)
```{r pop_den}
denMad <- read.csv("Data/denBarriosMad.csv", sep = ";", stringsAsFactors = FALSE)
colnames(denMad) <- c("Barrio", "Densidad")
```
---
## 2. ... and plot some meaningful data (atributos asociados)
#### Get ready both data frames.
```{r pop_den_2}
head(denMad)
head(barriosMadrid@data)
````
---
## 2. ... and plot some meaningful data (atributos asociados)
#### Get ready both data frames: denMad
```{r pop_den_3}
# Get rid off the 'distritos'
# 'barrios' have the structure ##.# Barrioname
# remove the "."
denMad <- denMad[which(grepl("[0-9]{2}\\.[0-9]", denMad$Barrio) == TRUE), ]
denMad$Barrio <- gsub(".", "", denMad$Barrio, fixed = TRUE)
head(denMad)
````
---
## 2. ... and plot some meaningful data (atributos asociados)
#### Get ready both data frames: denMad
```{r pop_den_4}
# Detach neighborhood name from neighborhood code
barriosNamesCodes <- do.call(rbind, strsplit(sub(" ", "\\.", denMad$Barrio), "\\."))
head(barriosNamesCodes)
denMad$Barrio <- barriosNamesCodes[ ,2]
denMad$BarrioCod <- barriosNamesCodes[ ,1]
```
---
## 2. ... and plot some meaningful data (atributos asociados)
#### Get ready both data frames: denMad
```{r pop_den_5}
head(denMad)
head(barriosMadrid@data)
```
---
## 2. ... and plot some meaningful data (atributos asociados)
#### Get ready both data frames: barriosMadrid SpatialPolygonDataFrame
```{r merge_data}
# Set the proper encoding
barriosMadrid$DESBDT <- iconv(barriosMadrid$DESBDT, "latin1", "UTF-8")
# Detach neighborhood name from neighborhood code
barriosNamesCodes <- strsplit(sub(" ", "\\.", barriosMadrid$DESBDT), "\\.")
barriosNamesCodes <- do.call(rbind, barriosNamesCodes)
head(barriosNamesCodes)
````
---
## 2. ... and plot some meaningful data (atributos asociados)
#### Get ready both data frames: barriosMadrid SpatialPolygonDataFrame
```{r merge_data_2}
barriosMadrid$BarrioCod <- barriosNamesCodes[ ,1]
barriosMadrid$Barrio <- barriosNamesCodes[ ,2]
head(barriosMadrid@data)
````
---
## 2. ... and plot some meaningful data (atributos asociados)
#### Merge both data frames
```{r merge_data_3}
length(denMad$Barrio)
length(barriosMadrid$DESBDT)
identical(sort(barriosMadrid$BarrioCod), sort(denMad$BarrioCod))
barriosMadrid@data <- merge(barriosMadrid@data, denMad[ ,c(2,3)])
````
---
## 2. ... and plot some meaningful data (atributos asociados)
#### Merge both data frames
```{r merge_data_4}
head(barriosMadrid@data)
```
---
## 2. ... and plot some meaningful data (atributos asociados)
#### and plot!
```{r plot_data}
plot(barriosMadrid, col = barriosMadrid$Densidad)
````
---
## 2. ... and plot some meaningful data (atributos asociados)
#### and plot!
```{r plot_data_1}
# Plot with SP library using custom colors
library(RColorBrewer)
colors <- colorRampPalette(brewer.pal(9, "YlGnBu"))(16)
spplot(barriosMadrid, "Densidad", col.regions = colors)
```
---
## 2. ... and plot some meaningful data (atributos asociados)
#### and plot! Customized colors using the `plot` function
```{r plot_data_2}
# Cut the variable into breaks and assign a color to every interval.
cut <- cut(barriosMadrid$Densidad,breaks=c(0,25,50,75,100,150,200,250,300,350,500))
barriosMadrid$cut <- cut
colors <- colorRampPalette(brewer.pal(9, "YlGnBu"))(10)
cutColors <- cut(barriosMadrid$Densidad,breaks=c(0,25,50,75,100,150,200,250,300,350,500), labels = colors)
barriosMadrid$colors <- cutColors
head(barriosMadrid@data)
```
---
## 2. ... and plot some meaningful data (atributos asociados)
#### and plot! Customized colors using the `plot` function
```{r plot_data_3}
plot(barriosMadrid, col = as.character(barriosMadrid@data$colors))
legend("bottomleft", cex = .7, legend = levels(barriosMadrid$cut), fill = colors, title = "Population density Madrid (2013)")
```
---
## 2. ... and plot some meaningful data (atributos asociados)
#### and plot! Add neighborhoods labels
```{r labels}
# calculate the polygons centers
# the coordinates function gives the centers of an SpatialPolygonDataFrame
cents <- coordinates(barriosMadrid)
head(cents)
````
---
## 2. ... and plot some meaningful data (atributos asociados)
#### and plot!
```{r labels_1}
#png("labels.png", width = 2500, height = 2100)
plot(barriosMadrid, col = as.character(barriosMadrid@data$colors))
plot(parquesMadrid, pch = 20, cex = 4, col = "springgreen3", add = TRUE)
pointLabel(cents[ ,1], cents[ ,2], labels=barriosMadrid$Barrio)
legend("bottomleft", cex = .9, legend = levels(barriosMadrid$cut), fill = colors, title = "Population density Madrid (2013)")
#dev.off()
```
---
## 2. ... and plot some meaningful data (atributos asociados)
#### and plot!: density as points
```{r den_as_points}
# maptools function
# plot as many dots as people living in every polygon
dots <- dotsInPolys(barriosMadrid, barriosMadrid$Densidad)
# png("density.png", width = 2500, height = 2100)
plot(dots, pch = 16, cex = .1, col = "violetred3")
# dev.off()
```
---
## 2. ... and plot some meaningful data (atributos asociados)
#### and plot!: density as points over the neighborhood and include the parks
```{r den_as_points_1}
plot(barriosMadrid, col = "grey90")
plot(dots, pch = 16, cex = .1, col = "violetred3", add = TRUE)
plot(parquesMadrid, pch = 20, cex = 1, col = "springgreen3", add = TRUE)
```
---
## 2. ... and plot some meaningful data (atributos asociados)
#### and plot!: include the metro lines
```{r metro}
metroLines <- readShapeLines("Shapefiles/MAD_lineas_metro/lineas.shp", proj4string = ED50)
plot(barriosMadrid, col = "grey90")
plot(dots, pch = 16, cex = .1, col = "violetred3", add = TRUE)
plot(parquesMadrid, pch = 20, cex = 1, col = "springgreen3", add = TRUE)
plot(metroLines, col = "turquoise3", lwd = 2, add = TRUE)
```
---
## 3. Plot a map on a street map (referencia)
#### ggplot2 + ggmap
The **rgdal** and **rgeos** libraries are required.
1. Change the coordinate system, as we have UTM in our objects and ggplot works on **long, lat** coordinates.
2. Create a dataframe from the Spatial**DataFrame data slot, containing the long and lat variables, as ggplot plots do not plot Spatial objects but dataframes.
3. and plot! (ggplot2 + ggmap)
---
## 3. Plot a map on a street map (referencia)
#### Change the coordinate system
```{r rgdal}
str(barriosMadrid, max.level = 2)
barriosMadrid@proj4string
# Transform the coordinates to lon lat
barriosLongLat <- spTransform(barriosMadrid, CRS("+proj=longlat"))
parquesLongLat <- spTransform(parquesMadrid, CRS("+proj=longlat"))
metroLongLat <- spTransform(metroLines, CRS("+proj=longlat"))
```
---
## 3. Plot a map on a street map (referencia)
#### Create a dataframe from the Spatial**DataFrame data slot.
#### Points DataFrame to ggplot
```{r ggplot}
library(ggplot2)
# Points DataFrame to ggplot
head(coordinates(parquesLongLat))
long <- coordinates(parquesLongLat)[, 1]
lat <- coordinates(parquesLongLat)[, 2]
```
---
## 3. Plot a map on a street map (referencia)
#### Create a dataframe from the Spatial**DataFrame data slot.
#### Points DataFrame to ggplot
```{r ggplot_4}
dataParques <- cbind(parquesLongLat@data, long, lat)
head(dataParques)
```
---
## 3. Plot a map on a street map (referencia)
#### Create a dataframe from the Spatial**DataFrame data slot.
#### Points DataFrame to ggplot
```{r ggplot_5}
ggplot(dataParques, aes(long, lat)) +
geom_point(colour = "springgreen3", size = 4)
```
---
## 3. Plot a map on a street map (referencia)
#### Create a dataframe from the Spatial**DataFrame data slot.
#### Polygons DataFrame to ggplot
```{r ggplot_8}
# The coordinates are the centers
head(coordinates(barriosLongLat))
barriosLongLat@data$id <- rownames(barriosLongLat@data)
head(barriosLongLat@data)
```
---
## 3. Plot a map on a street map (referencia)
#### Create a dataframe from the Spatial**DataFrame data slot.
#### Polygons DataFrame to ggplot
```{r ggplot_6}
# magic
dataBarrios <- fortify(barriosLongLat, region="id")
class(dataBarrios)
head(dataBarrios)
```
---
## 3. Plot a map on a street map (referencia)
#### Create a dataframe from the Spatial**DataFrame data slot.
#### Polygons DataFrame to ggplot
```{r ggplot_7}
dataBarrios <- merge(dataBarrios, barriosLongLat@data)
head(dataBarrios)
```
---
## 3. Plot a map on a street map (referencia)
#### Create a dataframe from the Spatial**DataFrame data slot.
#### Lines DataFrame to ggplot
```{r ggplot_9}
metroLongLat@data$id <- rownames(metroLongLat@data)
dataMetro <- fortify(metroLongLat, region="id") # requires rgeos package
dataMetro <- merge(dataMetro, metroLongLat@data)
head(dataMetro)
unique(dataMetro$ETIQUETA)
```
---
## 3. Plot a map on a street map (referencia)
#### Plot them! get the map
```{r, warning=FALSE, fig.width=5, fig.height=5}
library(ggmap)
MadridMap <- qmap(location = "Museo del Prado", zoom = 15, source = "google")
MadridMap
```
---
## 3. Plot a map on a street map (referencia)
#### Plot them! get the map
```{r warning=FALSE, fig.width=5, fig.height=5}
MadridMap <- qmap(location = barriosLongLat@bbox, zoom = 11, maptype = "terrain") # Get the map from Google maps
MadridMap
```
---
## 3. Plot a map on a street map (referencia)
#### Plot them! get the map
```{r, warning=FALSE, fig.width=5, fig.height=5}
MadridMap +
geom_polygon(aes( x = long, y = lat, group = group, fill = Densidad), data = dataBarrios, alpha = 0.5, colour = "white") +
scale_fill_gradient(low="grey90", high="black", limits=c(0,500)) +
geom_path(aes(x = long, y = lat, group = group), data = dataMetro, colour = "turquoise3") +
geom_point(aes(x = long, y = lat), data = dataParques, , size = 5, alpha = 0.8, colour = "springgreen3")+
theme(legend.position = "none")
```
---
## 4. Plot a map with ggplot without a background street map.
```{r, warning=FALSE, fig.width=5, fig.height=5}
ggplot() + geom_polygon(aes(x=long, y=lat, group = group, fill = Densidad), data = dataBarrios) +
scale_fill_gradient(low="grey90", high="black", limits=c(0,500)) +
geom_point(aes(x=long, y=lat, size = 5), data = dataParques, colour = "springgreen3") +
geom_path(aes(x=long, y = lat, group = group), data = dataMetro, colour = "turquoise3") +
theme(legend.position = "none",
panel.background = element_blank(),
panel.grid = element_blank(),
axis.ticks = element_blank(),
text = element_blank())
```
---
## 5. googleVis
```{r}
library(googleVis)
suppressPackageStartupMessages(library(googleVis))
emigrantes <- read.csv("Data/emigrantes.csv", sep = ";")
head(emigrantes)
# me quedo las que no empiezan por dos mayúsculas
emigrantes <- emigrantes[which(grepl("^[A-Z]{2}", emigrantes$pais) == FALSE), ]
head(emigrantes)
```
--- &interactive
## 5. googleVis
```{r opts.label = 'interactive', results = 'asis'}
emigrantesMap <- gvisGeoChart(emigrantes, locationvar = "pais", colorvar = "X2012", options = list(width = 600, height = 400))
print(emigrantesMap, tag = 'chart')
# plot(emigrantesMap)
# cat(emigrantesMap$html$chart, file="emigrantes2012.html")
```
---
## R to cartoDB
[walkerke RPubs](http://rpubs.com/walkerke/r2cartodb)