Spatial visualization with network graphs: Combining leaflet with networkD3?

Hi,

I was rather surprised when I found very few attempts on combining spatial visualization (fe with leaflet) with network graphs in r. I guess there is no easy way to combine leaflet with networkD3. Any pointers to alternative approach?

Thanks!

Made a working solution using leaflet & sp::SpatialLines. Might expand on it via a blogpost later.

library(dplyr)
library(readr)
library(janitor)
library(leaflet)
library(htmltools)
library(sp)
library(purrr)


cc = read_csv("http://techslides.com/demos/country-capitals.csv")

nodes = 
  cc %>% 
  clean_names() %>% 
  mutate(capital_latitude = as.numeric(capital_latitude)) %>% 
  select(capital_name, capital_longitude, capital_latitude) %>% 
  filter(capital_name %in% c("Warsaw", "El-AaiĂșn", "Jamestown", "Antananarivo", "Manama"))

edges = 
  full_join(
  nodes %>% rename(from = capital_name, from_lon = capital_longitude, from_lat = capital_latitude) %>% mutate(index = 1),
  nodes %>% rename(to = capital_name, to_lon = capital_longitude, to_lat = capital_latitude) %>% mutate(index = 1),
  by = "index") %>% 
  mutate(from_to = paste(from, "_", to)) %>% 
  filter(from != to) %>% 
  select(-index) %>% 
  rowwise() %>%  
  mutate(capital_lines = pmap(list(from_lon = from_lon, from_lat = from_lat, to_lon = to_lon, to_lat = to_lat, from_to = from_to),  
                             function(from_lon, from_lat, to_lon, to_lat, from_to) {
                               Line(cbind(c(from_lon, to_lon), 
                                          c(from_lat, to_lat))) %>% 
                                 Lines(., ID = from_to)}
  )) %>% 
  mutate(capital_lines = list(SpatialLines(list(capital_lines))))

  

nodes %>% 
  leaflet() %>% 
  addTiles() %>% 
  addCircleMarkers(lng = ~capital_longitude, lat = ~capital_latitude,opacity = 1, fillOpacity = 1, stroke = F, popup = ~htmlEscape(capital_name)) %>% 
  addPolylines(data = do.call(rbind, edges$capital_lines))

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.