christophergandrud / networkD3

D3 JavaScript Network Graphs from R
http://christophergandrud.github.io/networkD3
652 stars 268 forks source link

Manually setting colors (RGB/HEX) for group values in a forceNetwork diagram #301

Closed mvolar closed 9 months ago

mvolar commented 9 months ago

Hello,

i just adore the package and use it to visualize a lot of data,

however when trying to connect visualizations created by this plot and my other plots, often the limiting factor is that I just can't seem to get the color to match (i.e. ggplot2 colors to this plot) or something similar to discern the patterns. I have a relatively low number of groups (10ish) so manually inputting the colors shouldn't be a problem, I was wondering is there a straightforward way to put in my own colors for my grouping variables, either as a separate value in the dataframe or manually in the rendered html?

cjyetman commented 9 months ago

here's a reproducible example

library(networkD3)

links <- 
  read.csv(text = "
    source,target,value,color
    0,1,1,#F00
    0,2,1,#00F")

nodes <- 
  read.csv(text = "
    node_id,node_label,node_group
    0,Oranges,Orange_node
    1,Apples,Apple_node
    3,Pears,Pear_node")

forceNetwork(
  Links = links,
  Nodes = nodes,
  Source = "source",
  Target = "target",
  Value = "value",
  NodeID = "node_label",
  Group = "node_group",
  opacity = 1,
  opacityNoHover = 1,
  linkWidth = 4,
  fontSize = 18,
  colourScale = JS('d3.scaleOrdinal(["#FFA500", "#F00", "#90ee90"], ["Orange_node", "Apple_node", "Pear_node"]);'),
  linkColour = links$color
)

mvolar commented 9 months ago

Thank you very much for the solution! And the quick response!

I have little experience with JS but this is so elegant.