Search code examples
rechartssankey-diagramgooglevisnetworkd3

How to assign levels to nodes in multi-level sankey diagram?


I am trying to build interactive multi-level sankey diagram using R. I can't find the solution how to assign the levels to nodes. For example, a1 node should be on the second level in chart but not in the fifth. It seems that the package assigns to the last node in the chain the rightmost position, which is not preferable in my case. enter image description here

I tried different packages like echarts4r, networkD3, ggvis but it seems that these packages doesn't provide the functionality to manage levels in graph.

If you know how to solve this issue, please, share.

library('networkD3')
library('echarts4r')
library('googleVis')

sankey <- data.frame(
  source = c("a", "a", "b", "c", "d", "c"),
  target = c("b", "a1", "c", "d", "e", "e"),
  value = ceiling(rnorm(6, 10, 1)),
  stringsAsFactors = FALSE
)

# googleVis solution
plot(gvisSankey(sankey, from = 'source', to = 'target', weight = 'value'))

# echarts4r solution
sankey %>%
  e_charts() %>%
  e_sankey(source, target, value, focusNodeAdjacency = 'allEdges')


# networkD3 solution
nodes <- data.frame(name = c("a", "a1", "b", "c", "d", "e"))
links <- data.frame(
  source = c(0, 0, 2, 3, 4, 3),
  target = c(2, 1, 3, 4, 5, 5),
  value = ceiling(rnorm(6, 10, 1))
)

sankeyNetwork(Links = links, 
              Nodes = nodes, 
              Source = "source",
              Target = "target", Value = "value", NodeID = "name",
              fontSize = 12, nodeWidth = 30, sinksRight = TRUE)

Solution

  • Using , change sinksRight = TRUE to sinksRight = FALSE

    library('networkD3')
    
    sankey <- data.frame(
      source = c("a", "a", "b", "c", "d", "c"),
      target = c("b", "a1", "c", "d", "e", "e"),
      value = ceiling(rnorm(6, 10, 1)),
      stringsAsFactors = FALSE
    )
    
    sankeyNetwork(Links = links, 
                  Nodes = nodes, 
                  Source = "source",
                  Target = "target", Value = "value", NodeID = "name",
                  fontSize = 12, nodeWidth = 30, sinksRight = FALSE)
    
    

    enter image description here