I'm currently trying to make a flow map in leaflet for R to map the movement of something from one area (polygon) to another.
library(sp)
library(rgdal)
library(tidyverse)
library(leaflet)
I'm using this shapefile of local authorities (LAs) in England for the polygons, and I'm deriving the lines coordinates from those.
Map <- readOGR(dsn = "Map", layer = "LEA_Boundaries")
Map <- Map[!is.na(Map$lad16cd),]
I'm wanting to create lines from the centre of one polygon to another so I used the origin and destination polygons latitude and longitude(s) to derive the beginning and end point of my line. I did this through sampling the LA names from the Map's data slot, then sampling them again to create my starting and ending LAs, then merging the coordinates for the starting LA on, followed by the coordinates for the ending LA, as follows:
StartingLA <- sample(Map@data$lad16nm, 100000, replace = TRUE)
NextLA <- sample(StartingLA, 100000, replace = TRUE)
Movement <- data.frame(StartingLA, NextLA)
LD <- merge(Movement, Map@data[,c("lad16nm", "long", "lat")], by.x = "StartingLA", by.y = "lad16nm") %>%
merge(Map@data[,c("lad16nm", "long", "lat")], by.x = "NextLA", by.y = "lad16nm", suffixes = c("",".y"))
After this I have tried two separate ways to create spatial lines, one was a custom function to add a bezier line, and the other was gcIntermediate()
, which I'll use here a it's more accessible and rules out programming errors in the function.
flow <- gcIntermediate(LD[,c("long", "lat")], LD[,c("long.y", "lat.y")], sp = TRUE, addStartEnd = TRUE)
And now for the map itself; we'll add popup labels to the polygons so we can see which LAs are which.
leaflet() %>%
addProviderTiles(providers$CartoDB.PositronNoLabels) %>%
addPolygons(data = Map, weight = 1, col = "#000000", fillOpacity = 0, popup = Map@data$lad16nm) %>%
addPolylines(data = flow)
And we'll take a look at the data that was used to create the line.
LD
On my map I now have a blue line joining one polygon to the next. However for the StartingLA
in LD
, I have 'East Sussex', and the
NextLA
is 'Hillingdon', but the line points to/from Birmingham and Wandsworth.
This was also true using my custom function to fit bezier lines, which makes me think that it could be something that happened before, but all the data is correct right up until the lines are made into SpatialLines, and after that it all goes haywire.
Does anyone have any insight as to where I'm going wrong here?
Thank you.