Reputation: 1101
I have two shapefiles that I read into R with sf
.
I would like to overlay the two maps, then coloring each electoral district in a shade of the same color, having one color for each region.
I can plot the two and play around with colors but cannot overlay and coloring.
Files can be accessed here from the Italian National Institute of Statistics : Reg1991_WGS84.shp: http://www.istat.it/storage/cartografia/confini_amministrativi/non_generalizzati/Limiti1991.zip CAMERA_PLURI_2017.shp: https://www.istat.it/storage/COLLEGI_ELETTORALI_2017.zip
library(sf)
italia_regions_1991<- read_sf("Limiti1991/Reg1991/Reg1991_WGS84.shp") %>% select(geometry)
italia_camera_pluri <- read_sf("COLLEGI_ELETTORALI_2017/CAMERA_PLURI_2017.shp") %>% select(geometry)
Upvotes: 1
Views: 1324
Reputation: 8699
Consider intersecting the regions & districts via sf::st_intersection
- note however that there seems to be some overlap, as the regions and districts do not align perfectly (they mostly do, but not quite...)
I have also transformed the CRS to WGS84; perhaps not necessary, but works better with leaflet and the like...
library(sf)
library(dplyr)
library(ggplot2)
italia_regions_1991<- read_sf("Reg1991_WGS84.shp") %>%
select(region = DEN_REG) %>% # this, and geometry by default
st_transform(4326)
italia_camera_pluri <- read_sf("CAMERA_PLURI_2017.shp") %>%
select(geometry) %>% # only geometry...
st_transform(4326)
result <- italia_camera_pluri %>%
st_intersection(italia_regions_1991)
ggplot(data = result, aes(fill = region)) +
geom_sf()
Upvotes: 1
Reputation: 27732
This will get you started....
I used the leafgl
library, since you are plotting alot of polylines/plygons... This performs (pretty)fast...
library(sf)
library(devtools)
library(leaflet)
#install leaflet with gl-suport
devtools::install_github("r-spatial/leafgl")
library(leafgl)
library(colourvalues)
#read shapefile regions and cast to polygons
sf1 <- st_read( "e:/two_shapes/Limiti1991/Reg1991/Reg1991_WGS84.shp" ) %>% st_cast( "POLYGON", warn = FALSE )
#read shapefile and cast to POLYGON and then to LINESTRING
sf2 <- st_read( "e:/two_shapes/COLLEGI_ELETTORALI_2017/COLLEGI_ELETTORALI_2017.shp") %>%
st_cast( "POLYGON", warn = FALSE ) %>%
st_cast( "LINESTRING", warn = FALSE )
#creaae color matrix for the regions( depending om DEN_REG), and for the polylines (=black)
col_region <- colour_values_rgb(sf1$DEN_REG, include_alpha = FALSE) / 255
col_lines <- matrix(data = c(0,0,0), nrow = 1 )
#plot leaflet (takes some time)
leaflet() %>% addTiles() %>%
addGlPolygons(data = sf1, color = col_region) %>%
addGlPolylines( data = sf2, color = col_lines)
result
Upvotes: 4