Aula 7 Objetivos

  • Entender shapefiles em R
  • Tornando os dados espaciais
  • Visualizando mapas
  • Mapas Interativas

Shapefiles em R

  • Dois formatos: sp e sf (simple features)
  • sf funciona com o tidyverse
    • fluxo de trabalho mais fácil
    • somente um tipo de objeto para polygons/lines/points
  • Algumas estatísticas espaciais só funcionam com sp
  • Podemos converter:
    • sf <- sp %>% st_as_sf()
    • sp <- sf %>% as("Spatial")

Shapefiles em R

shapefile <- read_sf("Brazil_s.shp")

Shapefiles em R

  • dados espaciais residem numa coluna 'geometry'
OBJECTID ID CD_GEOCODM NM_MUNICIP Shape_Leng Shape_Area geometry
1 1 1700251 ABREULÂNDIA 3.4937977 0.1560446 list(list(c(-49.364354444502, -49.2685022924468, -49.2654451874454, -49.223640753418, -49.1924169844562, -49.1534104519308, -49.0846362238826, -48.9713559048511, -48.9559114192766, -48.905299254457, -48.9076912811277, -48.8756379460343, -48.8893772414665, -48.8681897221779, -48.886495800141, -48.9404954395129, -49.0956087730264, -49.1660253636795, -49.2659187506498, -49.3157212684218, -49.4249107855043, -49.4329459527934, -49.4635614760812, -49.5662265897852, -49.5666414893132, -49.5978101622092,
-49.6616704 17255 9, -49.731677 6724866, -49.723 0297053566, - 49.7070583330 756, -49.7256428933048, -49.701724316424, -49.7192512757258, -49.7040578637793, -49.6212182380312, -49.5946102295784, -49.5487200756709, -49.5233326666692, -49.4601131183257, -49.4518404041113, -49.3920827096493, -49.364354444502, -9.2491933075251, -9.35070680697351, -9.41212063086238, -9.49459682078663, -9.50239951782345, -9.56971404276879, -9.56553518370174, -9.59763845455097, -9.64726942304537, -9.65606545545637, -9.67576647993906,
-9.68016358 73795 8, -9.7067989 1184028, -9.7508 1225078469, - 9.77194564167 797, -9.71831657245178, -9.72487488836538, -9.74313873326588, -9.70990877736813, -9.62345375378766, -9.51669598013535, -9.47892231201502, -9.44177128231877, -9.40119381044593, -9.36408909583508, -9.31547467871343, -9.31584179636178, -9.34880965024513, -9.30195986485586, -9.29433032958099, -9.26966189528019, -9.20916615959055, -9.18137266121931, -9.16353089513467, -9.22094131409034, -9.26109451549945, -9.27473647820585, -9.25772478367179,
-9.27832144 29801 4, -9.2407155 9105164, -9.1614 8248233065, - 9.24919330752 51)))
2 2 1700301 AGUIARNÓPOLIS 0.6793842 0.0192433 list(list(c(-47.5764830883238, -47.5425387451669, -47.494793953578, -47.4660965538129, -47.4318990515, -47.4166526389081, -47.4564976507459, -47.4651223083478, -47.5041346945605, -47.5775799158804, -47.6350627815221, -47.6214158230817, -47.5764830883238, -6.41472972479693, -6.43726033209862, -6.43485234785754, -6.45182294247479, -6.42546832340435, -6.48567835707047, -6.53827451085994, -6.58710831399742, -6.57548030926881, -6.50000733167298, -6.45005938453295, -6.43072855787659, -6.41472972479693)))

Shapefiles em R

  • Para transformar os nossos dados para um outro projection
shapefile <- shapefile %>% st_transform(4326)
## Simple feature collection with 5567 features and 6 fields
## geometry type:  MULTIPOLYGON
## dimension:      XY
## bbox:           xmin: -73.98761 ymin: -33.74465 xmax: -28.83732 ymax: 5.271841
## epsg (SRID):    4326
## proj4string:    +proj=longlat +datum=WGS84 +no_defs

Shapefiles em R

  • Para transformar os nossos dados para um outro projection
shapefile <- shapefile %>% st_transform("+proj=utm +datum=WGS84 +zone=45")
## Simple feature collection with 5567 features and 6 fields
## geometry type:  MULTIPOLYGON
## dimension:      XY
## bbox:           xmin: -8004892 ymin: -19995880 xmax: -1635900 ymax: 19995700
## epsg (SRID):    32645
## proj4string:    +proj=utm +zone=45 +datum=WGS84 +units=m +no_defs

Shapefiles em R

  • Para manipular um shapefile, podemos usar todas as ações do tidyverse
shapefile %>% mutate(AreatoLength=Shape_Area/Shape_Leng) %>% 
  filter(CD_GEOCODM==1700251) %>% 
  select(CD_GEOCODM,NM_MUNICIP,AreatoLength)
## Simple feature collection with 1 feature and 3 fields
## geometry type:  MULTIPOLYGON
## dimension:      XY
## bbox:           xmin: -49.73168 ymin: -9.771946 xmax: -48.86819 ymax: -9.161482
## epsg (SRID):    NA
## proj4string:    +proj=longlat +ellps=GRS80 +no_defs
## # A tibble: 1 x 4
##   CD_GEOCODM NM_MUNICIP  AreatoLength                             geometry
##   <chr>      <chr>              <dbl>                  <MULTIPOLYGON [°]>
## 1 1700251    ABREULÂNDIA       0.0447 (((-49.36435 -9.249193, -49.2685 -9~

Shapefiles em R

  • Às vezes temos uma lista de coordenadas e precisamos criar um shapefile de pontos nós mesmos
  • Por exemplo, com 'georeferencing' de endereços
library(ggmap)
addresses <- c("Prefeitura, Recife, Brazil",
               "Caruara, Pernambuco, Brazil")
df <- geocode(addresses)
sf_points <- df %>% st_as_sf(coords = c("lon", "lat"), crs = 4326)
## Simple feature collection with 2 features and 0 fields
## geometry type:  POINT
## dimension:      XY
## bbox:           xmin: -35.97019 ymin: -8.284964 xmax: -34.87859 ymax: -8.047961
## epsg (SRID):    4326
## proj4string:    +proj=longlat +datum=WGS84 +no_defs
##                      geometry
## 1 POINT (-34.87859 -8.047961)
## 2 POINT (-35.97019 -8.284964)

Tornando os dados espaciais

  • Um shapefile sf é um data.frame!
  • Podemos join como normal - com colunas do mesmo nome, tipo, e valores
  • Lembre-se que precisamos uma tabela de dados com uma linha por cada spatial feature (polygon/point)
data <- cepespdata(year=2014, 
                   position="Governor",
                   regional_aggregation="Municipality",
                   political_aggregation="Candidate",
                   state="PE")

data <- data %>%
  group_by(COD_MUN_IBGE) %>%
  mutate(Vote_Pct=(QTDE_VOTOS/sum(QTDE_VOTOS))*100) %>%
  ungroup() %>%
  filter(NOME_URNA_CANDIDATO=="PAULO CÂMARA")

dim(data)
## [1] 185  59

Tornando os dados espaciais

shapefile <- shapefile %>% 
  separate(CD_GEOCODM,into=c("State","Mun"),sep=2, remove=FALSE) %>% 
  filter(State==26) %>% 
  mutate(COD_MUN_IBGE=as.numeric(CD_GEOCODM))

dim(shapefile)
## [1] 185  10

Tornando os dados espaciais

merged <- shapefile %>% left_join(data,by="COD_MUN_IBGE")
COD_MUN_IBGE NM_MUNICIP NOME_CANDIDATO QTDE_VOTOS geometry
2600054 ABREU E LIMA PAULO HENRIQUE SARAIVA CÂMARA 43427 list(list(c(-35.1400631323951, -35.1015711011128, -35.1040651675607, -35.0683750334682, -35.0541057378768, -34.9772358973058, -34.9181143068164, -34.8609864125792, -34.8620044505314, -34.8965077780981, -34.9085319000139, -34.9618921483908, -35.0318992102677, -35.0974237039283, -35.1400631323951, -7.79445273750751, -7.83062689122202, -7.8019885922036, -7.8117165030182, -7.88003762474093, -7.90002509138953, -7.88603824137654, -7.89722064282344, -7.9105669255283, -7.91786489515381, -7.93604072700305,
-7.915583054319 33, -7.92702580859882, - 7.88448024507149, -7.79445273750 751)))
2600104 AFOGADOS DA INGAZEIRA PAULO HENRIQUE SARAIVA CÂMARA 9313 list(list(c(-37.6559588774955, -37.6339675882289, -37.6116314584202, -37.55880525985, -37.5566143854407, -37.5379024587266, -37.5218848873728, -37.5769755905463, -37.6120577451642, -37.6172536097617, -37.6928289571861, -37.6826593794223, -37.7091701207999, -37.6827578309046, -37.696972615889, -37.6801498940977, -37.7048312516563, -37.684698062461, -37.6559588774955, -7.61387569650631, -7.63847558448083, -7.62642967379059, -7.63922325385029, -7.71505405909791, -7.71802781043547, -7.75334989338335,
-7.827491876149 69, -7.85010956390584, - 7.89457685453886, -7.81294440945 737, -7.80251 303544864, -7.7710379068743, -7.76103674155279, -7.7180864911989, -7.64538510993502, -7.6169291961256, -7.61454397552415, -7.61387569650631)))

Visualizando mapas

  • sf é fácil de usar com o ggplot
  • Mas precisamos instalar a versão de desenvolvimento do ggplot2
devtools::install_github("tidyverse/ggplot2")
library(ggplot2)

Visualizando mapas

merged %>% ggplot() +
  geom_sf() + 
  coord_sf()

Visualizando mapas

merged %>% ggplot() +
  geom_sf() +
  theme_classic() +
  coord_sf(datum=NA)

Visualizando mapas

merged %>% ggplot() +
  geom_sf(aes(fill=Vote_Pct)) +
  theme_classic() +
  coord_sf(datum=NA)

Visualizando mapas

merged %>% ggplot() +
  geom_sf(aes(fill=Vote_Pct), color="white") +
  theme_classic() +
  coord_sf(datum=NA)

Visualizando mapas

merged %>% rename("Vote %"="Vote_Pct") %>%
  ggplot() +
  geom_sf(aes(fill=`Vote %`), color="white") +
  theme_classic() +
  coord_sf(datum=NA)

Visualizando mapas

merged %>% rename("Vote %"="Vote_Pct") %>% 
  ggplot() +
  geom_sf(aes(fill=`Vote %`), color="white") +
  scale_fill_gradient(low="white",high="purple") +
  theme_classic() +
  coord_sf(datum=NA)

Visualizando mapas

merged %>% rename("Vote %"="Vote_Pct") %>% 
  ggplot() +
  geom_sf(aes(fill=`Vote %`), color="white") +
  scale_fill_gradient2(low="brown",mid="white", high="purple", 
                       midpoint=median(merged$Vote_Pct,na.rm=T)) +
  theme_classic() +
  coord_sf(datum=NA)

Visualizando mapas

merged %>% rename("Vote %"="Vote_Pct") %>% 
  ggplot() +
  geom_sf(aes(fill=`Vote %`), color="white") +
  geom_sf(data=sf_points, col="red",size=4) +
  theme_classic() +
  coord_sf(datum=NA)

Mapas Interativas

library(mapview)
merged %>% mapview()

Mapas Interativas

merged %>% mapview(zcol="Vote_Pct", legend=T)