Change the color of the legend text in forceNetwork for networkD3

老子叫甜甜 提交于 2020-01-14 03:04:14

问题


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;}')

回答1:


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");
  }'
)



来源:https://stackoverflow.com/questions/50677843/change-the-color-of-the-legend-text-in-forcenetwork-for-networkd3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!