logo
down
shadow

R: networkD3 sankey plot - colours not displaying


R: networkD3 sankey plot - colours not displaying

By : Nadine Miller
Date : October 23 2020, 08:10 PM
I think the issue was by ths following , The problem you're having must be with the data you are using, but I can't tell you precisely what because you haven't shared it. If I use properly structured data and use it as the inputs, your first, exact sankeyNetwork() command works as expected (with colors)...
(see further below for discussion of the NodeGroup parameter)
code :
library(networkD3)

URL <- paste0('https://cdn.rawgit.com/christophergandrud/networkD3/',
              'master/JSONdata/energy.json')
energy <- jsonlite::fromJSON(URL)

df_links <- energy$links
df_nodes <- energy$nodes

sankeyNetwork(Links = df_links, Nodes = df_nodes, Source = "source", 
              Target = "target", Value = "value", NodeID = "name", 
              units = "Cases", fontSize = 12, nodeWidth = 20)


Share : facebook icon twitter icon
NetworkD3 Sankey Plot in R: How to switch text labels from the right to the left of the inner nodes only

NetworkD3 Sankey Plot in R: How to switch text labels from the right to the left of the inner nodes only


By : ICE
Date : March 29 2020, 07:55 AM
wish of those help Starting from @timelyportfolio's answer, you can modify it to filter to any subset of nodes before applying the formatting...
code :
library(networkD3)
library(htmlwidgets)

links <- data.frame(
  src = c(0,0,1,1,2,2,3,3,4,4,5,5,6),
  target = c(3,6,4,5,5,6,7,9,8,9,7,10,7),
  value = 1
)

nodes <- data.frame(name = c(1, 2, 3,
                             "Middle 1", "Middle 2", "Middle 3", "Middle 4", 
                             4,5,6,7))

sn <- sankeyNetwork(
  Links=links, Nodes=nodes, Source='src', Target='target',
  Value='value', NodeID='name', fontSize=16,
  width=600, height=300,
  margin = list("left"=100)
)

sn

sn <- onRender(
  sn,
  '
  function(el,x){
  // select all our node text
  d3.select(el)
  .selectAll(".node text")
  .filter(function(d) { return d.name.startsWith("Middle"); })
  .attr("x", x.options.nodeWidth - 16)
  .attr("text-anchor", "end");
  }
  '
)

sn$jsHooks$render[[1]]
# $code
# [1] "\n  function(el,x){\n  // select all our node text\n  d3.select(el)\n  .selectAll(\".node text\")\n  .filter(function(d) { return d.name.startsWith(\"Middle\"); })\n  .attr(\"x\", x.options.nodeWidth - 16)\n  .attr(\"text-anchor\", \"end\");\n  }\n  "
# 
# $data
# NULL

sn
Modify networkD3 sankey plot with user-defined colors

Modify networkD3 sankey plot with user-defined colors


By : Kevin Bray
Date : March 29 2020, 07:55 AM
this will help The color pallete is determined by the colourScale argument. It should be a string containing valid D3 code to define the palette. In the current version of networkD3, which uses D3v4+, the syntax d3.scaleOrdinal().range(["#7d3945", "#e0677b", "#244457"]) is valid, though it could be shortened to d3.scaleOrdinal(["#7d3945", "#e0677b", "#244457"]). There are other possibilites as well, see here. The number of colors in the palette you choose/define must be equal to or greater than the total number of unique groups defined in your data, otherwise it will loop back to the beginning of your color palette to assign colors to further groups. The first group defined in your data will be assigned the first color in your color palette, and so forth.
The NodeGroup and LinkGroup parameters define the name of the column in your Nodes and Links data.frames, respectively, that define the group value for each node/link. Both nodes and links will be colored according to their group value and its assigned color based on the color palette being used.
code :
library(networkD3)

colors <- paste(networkD3_data$nodes$colors, collapse = '", "')
colorJS <- paste('d3.scaleOrdinal(["', colors, '"])')

sankeyNetwork(Links = networkD3_data$links, Nodes = networkD3_data$nodes, 
              Source = 'source', Target = 'target', Value = 'value', 
              NodeID = 'name', NodeGroup = "group", LinkGroup = "group",
              colourScale = colorJS,
              iterations = 0)
colors <- paste(sapply(networkD3_data$nodes$colors, function(x) { paste0("d3.rgb(", paste(c(col2rgb(x), 0.5), collapse = "," ), ")") }), collapse = ", ")
colorJS <- paste0('d3.scaleOrdinal([', colors, '])')
sankeyNetwork(Links = networkD3_data$links, Nodes = networkD3_data$nodes,
              Source = 'source', Target = 'target', Value = 'value',
              NodeID = 'name', NodeGroup = "group", LinkGroup = "group",
              colourScale = colorJS,
              iterations = 0)
How to set the color of nodes in the sankey plot using the networkD3 library

How to set the color of nodes in the sankey plot using the networkD3 library


By : Diego Carrasco
Date : March 29 2020, 07:55 AM
Hope this helps You need to add black color #000000 assignment to the node group 1 in your colourScale definition
code :
colourScale = JS('d3.scaleOrdinal().domain(["1", "a", "b", "c", "d", "e"]).
                 range(["#000000","#B3E2CD","#FDCDAC","#CBD5E8","#F4CAE4","#E6F5C9"])')
Sankey Diagram in R with networkD3 - row number issues

Sankey Diagram in R with networkD3 - row number issues


By : Ankur Agarwal
Date : March 29 2020, 07:55 AM
To fix this issue The reason is that ultimately the data gets sent to JavaScript/D3, which uses 0-based indexing... which means the index of the first element of a vector/array/etc. is 0... unlike in R where the index of the first element of a vector is 1.
code :
source <- c("A", "A", "B", "C", "D", "D", "E", "E")
target <- c("D", "E", "E", "D", "H", "I", "I", "H")

nodes <- data.frame(name = unique(c(source, target)))

links <- data.frame(source = match(source, nodes$name) - 1,
                    target = match(target, nodes$name) - 1,
                    value = 1)

library(networkD3)
sankeyNetwork(links, nodes, "source", "target", "value", "name")
Creating a Sankey Diagram using NetworkD3 package in R

Creating a Sankey Diagram using NetworkD3 package in R


By : Mengtian Wu
Date : March 29 2020, 07:55 AM
Does that help you need two dataframes: one listing all nodes (containing the names) and one listing the links. The latter contains three columns, the source node, the target node and some value, indicating the strength or width of the link. In the links dataframe you refer to the nodes by the (zero-based) position in the nodes dataframe.
Assuming you data looks like:
Related Posts Related Posts :
  • how to loop for division funciton in r
  • Why does ggplot not allow suppressing of messages generated by its geoms?
  • Download multiple excel files linked through urls in R
  • sparklyr : spark_apply function is not working in cluster mode
  • dplyr mutate - How do I pass one row as a function argument?
  • R selecting rows by conditions given in an external table
  • Native regex way to replace multiple leading chars with equal number spaces
  • stan - difficulty vectorizing
  • How to define a function that calls shiny functions?
  • How to count number of observations in a "n" dimensional range in R
  • Superimposing asymmetric t-distribution using ggplot2
  • Makefile to render all targets of all .Rmd files in directory
  • Authentication failure with rdrop2
  • DT data table display error
  • Issue when adding new rows (with nested dataframes within) to a dataframe
  • R-How to compare two dataframe and update list column value
  • Series vector for approximating pi
  • what is difference between "variance explained " in Random Forest and "merror" in XGBoost
  • R - Cast dataframe on unique rows - reshape2
  • ggplot2: plot correct proportions using geom_bar
  • Speedup query for R data.table - can this two-argument function be applied by group more quickly?
  • apply a function to several columns at once with mutate
  • R 'cowplot' neatly produce gridded plot with shared (common) legends and unique legends
  • Repeat R script for many times and save results to text file
  • How to negative lookbehind for special characters
  • data.table inner join produces error when no match is found
  • Create a new column base on existing column, but row above
  • Is there a way to visualize the process of source() in RStudio?
  • google places api consumes 10 request but I am doing only 1
  • Statistical mode of a categorical variable in R (using mlv)
  • Using for-loop to mutate a data.frame in r
  • Make plot with regression line for mixed model
  • Shortcut to select matces cases in R studio
  • vectoriced norm/matrix multiplication
  • Negative log10 transformation in R
  • Plot data with duplicate points
  • Visualizing crosstab tables with a plot in R - changing colours
  • How to manually modify automated numbers and labels in plot
  • How can I follow any redirections of a url in R?
  • Add jitter to box plot using markers in plotly
  • Adding an extra item to the legend
  • ggplot fills in data in the wrong order
  • Convert list to data frame
  • R: filtering by list(s) of strings and returning all results that start with the content of the lists
  • R:How to attach parts of a data frame with different headers and/or an overflowing piece of the dat frame
  • How to use 'par' for manipulating plot margins?
  • Can dplyr::case_when return mix of NAs and non-NAs?
  • Text preprocessing and topic modelling using text2vec package
  • Uploading multiple files in Shiny, process the files, rbind the results and return a download
  • R levelplot: color green-white-red (white on 0) according to one variable, but show the values of another variable
  • Why [i] doesn't point to the starting point in a vector
  • In R after generating a mvrnorm distribution, Y, what does Y[,1] do?
  • expand a data frame to have as many rows as range of two columns in original row
  • Getting started with R and CFA
  • Re order x-axis in ggplot so time goes from 12AM to 11PM in R
  • R - Automatically stack every nth column of a data frame and save them as new objects
  • How to format dplyr output in R into doubles (or other workable format)?
  • Dataframe to matrix conversion using tapply turns zeros to NAs
  • Smallest multiple of 1:20 - How can I make it quicker?
  • How to specify the size of a graph in ggplot2 independent of axis labels
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org