rplotlysankey-diagram

Subplot Sankey Diagrams in plotly R


I would like to show two Sankey Plotly R diagrams below or side by side using the subplot function. Unfortunately, this doesn't work for a Sankey Diagram. Here is some reproducible simple code:

library(plotly)

fig1 <- plot_ly(
  type = "sankey",
  orientation = "h",
  
  node = list(
    label = c("A1", "A2", "B1", "B2", "C1", "C2"),
    color = c("blue", "blue", "blue", "blue", "blue", "blue"),
    pad = 15,
    thickness = 20,
    line = list(
      color = "black",
      width = 0.5
    )
  ),
  
  link = list(
    source = c(0,1,0,2,3,3),
    target = c(2,3,3,4,4,5),
    value =  c(8,4,2,8,4,2)
  )
)

fig2 <- plot_ly(
  type = "sankey",
  orientation = "h",
  
  node = list(
    label = c("A1", "A2", "B1", "B2", "C1", "C2"),
    color = c("blue", "blue", "blue", "blue", "blue", "blue"),
    pad = 15,
    thickness = 20,
    line = list(
      color = "black",
      width = 0.5
    )
  ),
  
  link = list(
    source = c(0,1,0,2,3,3),
    target = c(2,3,3,4,4,5),
    value =  c(8,4,2,8,4,2)
  )
)

plotly::subplot(fig1, fig2, nrows = 2)

Output:

enter image description here

It just overlaps the plots and doesn't show it side by side or below each other. So I was wondering if anyone knows how to show Sankey Diagrams side by side in plotly R?


Solution

  • Sankey plots aren't supported in plotly subplots as it seems. But since plotly objects are Web Components, we can combine them using htmltools

    library(htmltools)    
    browsable(div(fig1, fig2))
    

    giving out


    sample data

    library(plotly)
    
    fig1 <- plot_ly(
      type = "sankey",
      orientation = "h",
      
      node = list(
        label = c("A1", "A2", "B1", "B2", "C1", "C2"),
        color = c("blue", "blue", "blue", "blue", "blue", "blue"),
        pad = 15,
        thickness = 20,
        line = list(
          color = "black",
          width = 0.5
        )
      ),
      
      link = list(
        source = c(0,1,0,2,3,3),
        target = c(2,3,3,4,4,5),
        value =  c(8,4,2,8,4,2)
      )
    )
    
    fig2 <- fig1