Para este trabajo práctico utilizaremos el portal de datos abierto de la ciudad de Londres (https://data.london.gov.uk/). Lo primero que haremos es cargar la biblioteca sf para poder trabajar mejor con archivos georeferenciados. Utilizamos como plano base un mapa de Londres con los distintos sectores marcados. Para poder utilizar este mapa vamos a transformarlo en Mercator con la funcion st_merkator. Con ggplot y plot vamos a ver un poco cómo es y qué informacion contiene.
options(scipen = 999)
library(sf)
## Linking to GEOS 3.6.1, GDAL 2.2.3, PROJ 4.9.3
library(raster)
## Loading required package: sp
library(dplyr)
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:raster':
##
## intersect, select, union
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
library(spData)
## To access larger datasets in this package, install the spDataLarge
## package with: `install.packages('spDataLarge',
## repos='https://nowosad.github.io/drat/', type='source')`
library(ggplot2)
library(lubridate)
##
## Attaching package: 'lubridate'
## The following object is masked from 'package:base':
##
## date
library(tidyverse)
## -- Attaching packages ------------------------------------------------------------------- tidyverse 1.3.0 --
## v tibble 2.1.3 v purrr 0.3.3
## v tidyr 1.0.2 v stringr 1.4.0
## v readr 1.3.1 v forcats 0.5.0
## -- Conflicts ---------------------------------------------------------------------- tidyverse_conflicts() --
## x lubridate::as.difftime() masks base::as.difftime()
## x lubridate::date() masks base::date()
## x tidyr::extract() masks raster::extract()
## x dplyr::filter() masks stats::filter()
## x lubridate::intersect() masks raster::intersect(), base::intersect()
## x dplyr::lag() masks stats::lag()
## x dplyr::select() masks raster::select()
## x lubridate::setdiff() masks base::setdiff()
## x lubridate::union() masks raster::union(), base::union()
MapaBaseLondres = st_read("London_Borough_Excluding_MHW.shx")
## Reading layer `London_Borough_Excluding_MHW' from data source `C:\Users\Fede\Documents\Ciencia de Datos para Ciudades 2\London_Borough_Excluding_MHW.shx' using driver `ESRI Shapefile'
## Simple feature collection with 33 features and 7 fields
## geometry type: MULTIPOLYGON
## dimension: XY
## bbox: xmin: 503568.2 ymin: 155850.8 xmax: 561957.5 ymax: 200933.9
## proj4string: +proj=tmerc +lat_0=49 +lon_0=-2 +k=0.999601272 +x_0=400000 +y_0=-100000 +datum=OSGB36 +units=m +no_defs
MapaBaseLondres <- MapaBaseLondres %>%
st_transform(crs = 4326)
ggplot() +
geom_sf(data = MapaBaseLondres)+ labs(title = "Londres", subtitle = "Plano Base", caption = "Fuente:https://data.london.gov.uk/", x= "Longitud",y = "Latitud") + theme(legend.position = "bottom")
plot(MapaBaseLondres)
Nos parecio interesante trabajar con la distribucion de las escuelas a lo largo de Londres. Para eso, bajamos un archivo .csv con información de todas las escuelas y sus coordenadas expresadas en x e y. Vamos a graficarlas sobre el mapa anterior con ggplot para vez como estan desplegadas en el territorio. Para poder identificar mejor la densidad le ponemos un alpha de 0.3 que le da transparencia y permite identificar de mejor manera la concentración.
UbicacionEscuela = read.csv("all_schools_xy_2016.csv")
ggplot() +
geom_sf(data = MapaBaseLondres)+
geom_point(data = UbicacionEscuela,
aes(x = x, y = y),
alpha = .3,
color = "Red",
size = 1) + labs(title = "Escuelas de Londres", subtitle = "Distribucion de las escuelas en la ciudad de Londres", caption = "Fuente: https://data.london.gov.uk/") + theme(legend.position = "bottom")
A continuación filtramos las escuelas para que que no quede ninguna sin coordenadas y le agregamos el identificador del sistemas de coordenadas.
GEOUbicacionEscuela <- UbicacionEscuela %>%
filter(!is.na(x), !is.na(y)) %>%
st_as_sf(coords = c("x", "y"), crs = 4326)
Esc_Map = st_join(GEOUbicacionEscuela, MapaBaseLondres)
## although coordinates are longitude/latitude, st_intersects assumes that they are planar
## although coordinates are longitude/latitude, st_intersects assumes that they are planar
Esc_Agrupado = Esc_Map %>%
group_by(NAME) %>%
summarise(cantidad = n())
## Warning: Factor `NAME` contains implicit NA, consider using
## `forcats::fct_explicit_na`
Esc_Agrupado
## Simple feature collection with 34 features and 2 fields
## geometry type: MULTIPOINT
## dimension: XY
## bbox: xmin: -0.570224 ymin: 51.2494 xmax: 0.366442 ymax: 51.729
## CRS: EPSG:4326
## # A tibble: 34 x 3
## NAME cantidad geometry
## * <fct> <int> <MULTIPOINT [°]>
## 1 Barking and D~ 65 ((0.0752504 51.5414), (0.0754681 51.5366), (0.076999~
## 2 Barnet 171 ((-0.288111 51.6233), (-0.281291 51.613), (-0.275321~
## 3 Bexley 87 ((0.0804312 51.4364), (0.0835056 51.4638), (0.088315~
## 4 Brent 108 ((-0.319624 51.5598), (-0.311277 51.5694), (-0.31057~
## 5 Bromley 133 ((-0.0690635 51.4111), (-0.0593407 51.4098), (-0.058~
## 6 Camden 111 ((-0.207929 51.5511), (-0.206991 51.5559), (-0.20018~
## 7 City of London 8 ((-0.099525 51.5111), (-0.0988945 51.5204), (-0.0968~
## 8 Croydon 159 ((-0.145975 51.3173), (-0.143984 51.3187), (-0.14127~
## 9 Ealing 124 ((-0.404162 51.5338), (-0.40279 51.536), (-0.39557 5~
## 10 Enfield 114 ((-0.173195 51.6702), (-0.158949 51.6849), (-0.14112~
## # ... with 24 more rows
ggplot() +
geom_sf(data = MapaBaseLondres) +
geom_sf(data = Esc_Agrupado, aes(color = NAME),alpha = .3,size = 1) + labs(title = "Escuelas de Londres", subtitle = "Distribucion de las escuelas en la ciudad de Londres", caption = "Fuente: https://data.london.gov.uk/") + theme(legend.position = "bottom")
# Como recortar los que no pertenecen al centro de la ciudad con FILTER
Escuelas_Recortadas <- Esc_Agrupado %>%
filter(!is.na(NAME)) %>%
group_by(NAME) %>%
summarise(cantidad=n())
plot(Escuelas_Recortadas)
Escuelas_Recortadas_Geo = st_intersection(GEOUbicacionEscuela, MapaBaseLondres)
## although coordinates are longitude/latitude, st_intersection assumes that they are planar
## Warning: attribute variables are assumed to be spatially constant throughout all
## geometries
ggplot() +
geom_sf(data = MapaBaseLondres) +
geom_sf(data = Escuelas_Recortadas_Geo, aes(color = NAME),alpha = .3,size = 1) + labs(title = "Escuelas en Londres", subtitle = "Distribución de las escuelas en la ciudad de Londres", caption = "Fuente:https://data.london.gov.uk/") + theme(legend.position = "bottom") + theme(text = element_text(size=7))
El mapa anterior nos brindaba una primera impresión sobre el ordenamiento espacial de las escuelas, pero puede que no sea tan útil si lo que queremos destacar es el número de instituciones educativas por borough.
Lo que vamos a hacer, entonces, es crear un nuevo dataset que sume el número de escuelas por barrio.
Escuelas_Recortadas_Geo_Suma <- Escuelas_Recortadas_Geo %>%
group_by(TOWN) %>%
summarise(SCHOOL_NAM=n())
Lo graficamos de la siguiente manera:
Escuelas_Recortadas_Geo_Suma <- Escuelas_Recortadas_Geo %>%
group_by(NAME) %>%
summarise(SCHOOL_NUM=n())
MapaLondresEscuelas= st_join(MapaBaseLondres, Escuelas_Recortadas_Geo_Suma, by = "NAME")
## although coordinates are longitude/latitude, st_intersects assumes that they are planar
ggplot() +
geom_sf(data = MapaLondresEscuelas, aes(fill = SCHOOL_NUM))
Nótese que en este primer intento de generar un gráfico obtenemos una escala de colores un tanto contraintuitiva, donde la menor presencia de escuelas es indicada con un color más claro. Para invertirlo, recurrimos al scale_fill_gradient con mayores y menores. También sumamos título, subtítulo y adaptamos la leyenda. El resultado es mucho más prolijo y acorde a lo buscado.
Escuelas_Recortadas_Geo_Suma <- Escuelas_Recortadas_Geo %>%
group_by(NAME) %>%
summarise(SCHOOL_NUM=n())
MapaLondresEscuelas= st_join(MapaBaseLondres, Escuelas_Recortadas_Geo_Suma, by = "NAME")
## although coordinates are longitude/latitude, st_intersects assumes that they are planar
ggplot() +
geom_sf(data = MapaLondresEscuelas, aes(fill = SCHOOL_NUM)) +
scale_fill_gradient(low = "#56B1F7", high = "#132B43") +
labs(title = "Escuelas en Londres por barrio", subtitle = "Número de las escuelas por borough", fill = "Escuelas", caption = "Fuente: https://data.london.gov.uk/") + theme(legend.position = "bottom") + theme(text = element_text(size=10))