Search code examples
rggplot2leafletmapsr-leaflet

Leaflet equivalent of geom_segments xend, yend arguments


I would like to ask is there a way how to set xend and yend from geom_segment arguments in leaflet`s addPolylines function?

insted of explaining I rather provide reproduceble example since it is mut easire to see rather than explain:

library(leaflet)
library(spdep)
library(ggplot2)

URL <- "https://biogeo.ucdavis.edu/data/gadm3.6/Rsp/gadm36_DEU_1_sp.rds"
data <- readRDS(url(URL))

cns <- knearneigh(coordinates(data), k = 1, longlat = T)
scnsn <- knn2nb(cns, row.names = NULL, sym = T)
cns
scnsn
cS <- nb2listw(scnsn)

# Plotting results
plot(data)
plot(cS, coordinates(data), add = T)

# Plotting in ggplot 
# Converting to data.frame
data_df <- data.frame(coordinates(data))
colnames(data_df) <- c("long", "lat")

n = length(attributes(cS$neighbours)$region.id)
DA = data.frame(
  from = rep(1:n,sapply(cS$neighbours,length)),
  to = unlist(cS$neighbours),
  weight = unlist(cS$weights)
)
DA = cbind(DA, data_df[DA$from,], data_df[DA$to,])
colnames(DA)[4:7] = c("long","lat","long_to","lat_to")


ggplot(data, aes(x = long, y =lat))+
  geom_polygon(aes(group = group), color = "black", fill = FALSE)+
  geom_point(data = data_df, aes(x= long, y = lat), size = 1)+
  geom_segment(data = DA, aes(xend = long_to, yend = lat_to), size=0.5, color = "red")

# Plotting in leaflet
leaflet() %>% addProviderTiles("CartoDB.Positron") %>% 
  addPolygons(data=data, weight = 0.8, fill = F, color = "red") %>% 
  addPolylines(data=DA, lng = DA$long_to, lat = DA$lat_to, weight = 0.85)

It can be seen then result in leaflet are not right (Spatial Map is different) how ever plots in basic plot and ggplot are how things should look like,

Is there a way how to reproduce plots above in leaflet? Reading leaflet documentation did not help me


Solution

  • A possible workaround is to use the function addFlows() implemented in library(leaflet.minicharts).

    leaflet() %>% addProviderTiles("CartoDB.Positron") %>% 
      addPolygons(data=data, weight = 0.8, fill = F, color = "red") %>% 
      addFlows(lng0 = DA$long, lat0 = DA$lat,lng1 = DA$long_to, lat1 = DA$lat_to, dir = 1, maxThickness= 0.85)