-
Notifications
You must be signed in to change notification settings - Fork 5
/
05-interactive-maps.Rmd
248 lines (180 loc) 路 7.92 KB
/
05-interactive-maps.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
# Putting you data on the map
Plots are nice, but interactive plots are nicer!
Objectives:
* To understand the use of interactive elements
* To be able to place simple markers on a leaflet map
* To be able to create popups with contents that depends on the data
## Interactive elements
The reports you create with Rmarkdown are just webpages underneath. This means
you can embed anything that your browser knows how to display. Including
interactive elements. These are useful if you have a lot of data or want to
let the reader explore the data themselves. A good starting point are the
[R htmlwidgets](http://www.htmlwidgets.org/index.html).
## DataTables
One of the most straightforward interactive element you can use is a table.
Interactive tables are a good way to quickly explore your data, especially for
others who are reading your report. The [`DT` library](https://rstudio.github.io/DT/)
uses HTML and javascript to create a table that let's the reader sort and search
the data.
```{r}
library(DT)
gapminder <- read.csv("data/gapminder-FiveYearData.csv")
datatable(gapminder)
```
![](../imgs/data-table.gif)
It really is this easy to use.
### Challenge
1. Create a new Rmarkdown document and ddd an interactive data table showing
the gapmidner data to it.
2. Using the search function, can you find out how many entries there are for
the continent of Asia?
## The mapview library
Quoting from the
[`mapview`](http://environmentalinformatics-marburg.github.io/mapview/introduction.html)
documentation:
---
`mapview` is an R package created to help researchers during their spatial
data analysis workflow. It provides functions to very quickly and conveniently
create interactive visualisations of spatial data.
`mapview` was created o fill the gap of quick (not presentation grade)
interactive plotting to examine and visually investigate spatial data.
So far, one had to either:
* (sp)plot the data in R and then toggle back and forth between
the static plots; or
* save the data to the disk and then open in QGIS or similar to
interactively examine the results.
---
This continues the theme of interactively exploring a new dataset or a new idea
on an old dataset. `mapview` is probably not the right tool to produce the
final product that you distribute to users, but it is extremely useful for
your day-to-day work and sharing with collaborators.
We will briefly switch away from the gapminder dataset to
one with information about all the cantons in Switzerland. This dataset contains
the outlines of the cantons, their names, and a few variations of their names.
Let's take a quick look at the data without using a map:
```{r}
library(mapview)
data("gadmCHE")
summary(gadmCHE@data)
```
`gadmCHE` itself is an object that knows about spatial representations and
the data itself. The data is stored in the `data` slot which we can access as
`gadmCHE@data`. It is not the most exciting dataset, but let's use it for a
moment.
```{r}
mapview(gadmCHE)
```
This uses `leaflet`, a very powerful JavaScript library to draw a interactive
map and draws the outlines of the cantons on top. Now we can click on a canton
and the popup shows all the columns for this canton. We can control what is
visible in the popup via:
```{r}
mapview(gadmCHE, popup=popupTable(gadmCHE, zcol = c("NAME_1")))
```
Now the popup only contains the value of the `NAME_1` field.
If your polygons are very large/complicated drawing their outlines will take
some time. Think drawing the outlines of all countries in the world. Luckily
it is fairly straightforward to obtain the centres of each polygon and draw
a marker there instead of the outline.
```{r}
m <- mapview(gadmCHE)
m
# create a data frame
centres <- data.frame(coordinates(gadmCHE))
names(centres) <- c("x", "y")
# next call turns it back into a spatial points object
coordinates(centres) <- ~ x + y
projection(centres) <- projection(gadmCHE)
m + centres
# join the spatial points with the data
pointsCHE <- sp::SpatialPointsDataFrame(centres, gadmCHE@data)
```
> ## Large data ahead
>
> The following examples use a fairly big data set that you
> need to download. It is only about 500MB but probably the
> conference WiFi will collapse if we all try and download it now.
>
> The data come from [GADM](http://gadm.org/version2) and you want to
> download the [six dissolved layers
> shapefile](http://biogeo.ucdavis.edu/data/gadm2.8/gadm28_levels.shp.zip)
## Loading a shapefile
The `rgdal` library can read most of the common file formats in which geographic
information is stored (GeoJSON, shapefiles, etc). To load our shapefile with
adm0 level boundaries (fancy speak for outlines of countries):
```{r}
world <- rgdal::readOGR("/Users/thead/Downloads/gadm28_levels/", layer="gadm28_adm0")
keep <- c("NAME_LOCAL", "POPSQKM") # columns to keep
eu <- world[world$EU==1, (names(world) %in% keep)]
```
This reads in the file `/Users/thead/Downloads/gadm28_levels/gadm28_adm0.shp`
which contains high quality outlines and some other information. To make it a
bit more manageable I removed all but the local name and population density.
Then select only those countries which are in the EU. This is mainly to
keep things moving at a good pace for the tutorial.
We can now show the outline of the countries in the EU and colour them
by their population density.
```{r}
mapview(eu, zcol="POPSQKM", at=seq(0,500, 100), legend=TRUE)
```
This command also set the range of the colour scale. There is a surprising
range of population densities in the EU (from 10people/km^2 to 1100people/km^2)
wich makes it a bit tricky to display.
The material below are simply variations on the above but using real data.
Computing the centres of the EU countries, then using those on the map to
speed up plotting, followed by doing the same for the whole world and then
finally returning to our gapminder dataset, joining it with the outlines of
countries and displaying it.
```{r}
library(sp)
library(rgdal)
library(raster)
# create a SpatialPointsDataFrame
eu.centers <- data.frame(coordinates(eu))
names(eu.centers) <- c("x", "y")
coordinates(eu.centers) <- ~x+y
projection(eu.centers) <- projection(eu)
mapview(eu.centers)
# put the data back
euPoints <- sp::SpatialPointsDataFrame(eu.centers, eu@data)
mapview(euPoints)
mapview(euPoints, cex='POPSQKM', legend=TRUE)
```
This is the exciting part, an overview of the whole world showing
population density and GDP per capita:
```{r}
# join gadm dataset with gapminder
gm <- read.csv("gapminder.csv")
gm$NAME = toupper(gm$country)
df <- gm[gm$year==2007,]
world@data = data.frame(world@data, df[match(world@data[,"NAME_ISO"], df[,"NAME"]),])
# using points for a world wide view
wp <- SpatialPointsDataFrame(coordinates(world), world@data)
projection(wp) <- projection(world)
mapview(wp, cex='POP2000', zcol=c('POPSQKM', "gdpPercap"), legend=TRUE)
```
## Leaflet
[Leaflet](http://leafletjs.com/) is a javascript library that is commonly
used to create interactive webmaps. Together with openlayers I would claim it
is the "industry standard" for making interactive maps. There is an R library
that allows you to use `leaflet` without having to know any javascript.
Use this if you want ultimate control over your map. In exchange it is a
little less easy to use than `mapview`.
## Resources
Hungry for more? Keep reading:
Consult the [spatial R cheatsheet
](http://www.maths.lancs.ac.uk/~rowlings/Teaching/UseR2012/cheatsheet.html) if
you need to refresh your memory.
Take a look at the [geospatial packages](https://ropensci.org/packages/) created
by Ropensci.
http://rstudio.github.io/leaflet/
http://www.htmlwidgets.org/showcase_datatables.html
http://www.htmlwidgets.org/showcase_dygraphs.html
http://journocode.com/2016/01/28/your-first-choropleth-map/
https://rpubs.com/walkerke/leaflet_choropleth
HOTOSM does amazing work producing maps during disasters. A source
of up-to-date shapefiles is http://export.hotosm.org/en/exports/create/
## Write to ESRI shapefiles
```{r}
rgdal::writeOGR(eu, '/tmp/', layer='eu', driver='ESRI Shapefile')
```