3

I am creating a Sankey diagram in Shiny using networkD3 library. I need to change the position of one node (rotate it on 90d and move down). For this, I use js as in the little example below. However, after changing the node I need to update the link and I have no idea how to do that.

library(shiny)
library(networkD3)
library(htmlwidgets)
library(tibble)
library(dplyr)
library(ggplot2)
library(ggforce)


ui <- fluidPage(
  fluidRow(sankeyNetworkOutput("plot"))
)

server <- function(input, output, session) {
  session$onSessionEnded(stopApp)

  URL <- paste0(
    "https://cdn.rawgit.com/christophergandrud/networkD3/",
    "master/JSONdata/energy.json"
  )
  energy <- jsonlite::fromJSON(URL)
  
  output$plot <- renderSankeyNetwork({
    sn <- sankeyNetwork(
      Links = energy$links, Nodes = energy$nodes, Source = "source",
      Target = "target", Value = "value", NodeID = "name",
      units = "TWh", fontSize = 12, nodeWidth = 30, nodePadding = 0,
      width = "100%", sinksRight = FALSE
    )

    update_diagr <-
      'function(el, x) {
          d3.select(el)
          .selectAll(".node rect")
          .filter(function(d) { return d.name.startsWith("National"); })
          .attr("transform", "translate(0 100) rotate(90)");
          
        }'
    onRender(sn, update_diagr)
  })
}

shinyApp(ui, server)

enter image description here

Olena
  • 97
  • 1
  • 8

1 Answers1

0

You can try Plotly for alternative. You can try specifying X,Y coordinates of each node to position them. This way links won't disappear. Documentation: https://plotly.com/r/sankey-diagram/#define-node-position

ubergeek
  • 27
  • 1
  • 4
  • 1
    Yes, it works for plotly. But not for networkD3. Also, it's very hard to calculate a specific position of nodes for such types of graphic, with complex structure. – Olena Mar 13 '21 at 08:11
  • I see. I did position nodes in fairly complex Sankey plot but I only used plotly that too in R and Python. – ubergeek Mar 14 '21 at 09:36