Smith
Smith

Reputation: 119

Change the color of the legend text in forceNetwork for networkD3

Using forceNetwork from the networkD3 R package, how can I change the color of the text in the legend to white?

My Code:

library(networkD3)

forceNetwork(Links = subLinkList, Nodes = subNodes, 
             Source = "root", Target = "children", 
             Value = "linkValue", NodeID = "nodeName", 
             Nodesize = "nodeSize", Group = "nodeGroup", 
             colourScale = JS(colorScale), charge = -500, 
             opacity = 1, opacityNoHover = 1, fontSize = 25, 
             fontFamily = "Calibri",
             linkDistance = JS('function(){d3.select("body").style("background-color", "#144370");return 200;}'), 
             linkWidth = 3, linkColour = "white", 
             legend = TRUE, bounded = TRUE, zoom = TRUE)

What I tried:

linkDistance = JS('function(){d3.select("body").style("background-color", "#144370").legend.text("fill", "white");return 200;}')

Upvotes: 1

Views: 1058

Answers (1)

CJ Yetman
CJ Yetman

Reputation: 8848

this is a fully replicable example, using a better method to add custom JavaScript than overloading the linkDistance argument with extra code...

library(networkD3)
library(htmlwidgets)

subNodes <- 
  read.table(stringsAsFactors = FALSE, header = TRUE, text = "
  nodeName nodeGroup     nodeSize
  Bob      NorthAmerica  10
  Alice    NorthAmerica  10
  Tom      China         10
  John     Japan         10
  ")

subLinkList <-
  read.table(stringsAsFactors = FALSE, header = TRUE, text = "
  root  children  linkValue
  0     1         1
  0     2         1
  0     3         1
  ")

colorScale <- "d3.scaleOrdinal(d3.schemeCategory20);"

fn <- forceNetwork(Links = subLinkList, Nodes = subNodes, 
             Source = "root", Target = "children", 
             Value = "linkValue", NodeID = "nodeName", 
             Nodesize = "nodeSize", Group = "nodeGroup",
             colourScale = JS(colorScale),
             charge = -500, opacity = 1, opacityNoHover = 1, fontSize = 25,
             fontFamily = "Calibri", linkDistance = 200,
             linkWidth = 3, linkColour = "white",
             legend = TRUE, bounded = TRUE, zoom = TRUE)

htmlwidgets::onRender(
  fn,
  'function(el, x) { 
    d3.select("body").style("background-color", "#144370");
    d3.selectAll(".legend text").style("fill", "white");
  }'
)

forceNetwork example output

Upvotes: 2

Related Questions