All examples By author By category About

timelyportfolio

d3_table example with sankey

I was reminded recently by an email of a function that I wrote a couple of year ago to convert a R table to d3 nodes and links network. I thought this functionality might be helpful in d3r, so I added d3_table(). Hopefully, d3r 0.6.6 with d3_table() hits CRAN tonight or tomorrow.

This quick example makes a d3/networkD3 sankey and visNetwork out of a table constructed from diamonds.

Code in R

# hopefully d3_table hits CRAN tonight
# devtools::install_github("timelyportfolio/d3r")

library(d3r)
library(pipeR)
library(networkD3)
library(visNetwork)

data(diamonds, package="ggplot2")

dia_tbl <- xtabs(~cut+clarity,diamonds)

d3_table(dia_tbl) %>>%
  (sankeyNetwork(
    Links = .$links
    , Nodes = .$nodes
    , Source= "source"
    , Target = "target"
    , Value = "value"
    , NodeID = "name"
  ))

d3_table(dia_tbl) %>>%
  (
    visNetwork(
      nodes = data.frame(
        id = as.numeric(rownames(.$nodes))-1
        ,label = .$nodes$name
        ,value = .$nodes$value
      )
      ,edges = data.frame(
        from = .$links$source
        ,to = .$links$target
        ,value = .$links$value
      )
    )
  )