更改forceNetwork for networkD3中图例文本的颜色

时间:2018-06-04 09:53:35

标签: javascript r d3.js htmlwidgets networkd3

使用forceNetwork R套餐中的networkD3,如何将图例中的文字颜色更改为白色?

我的代码:

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)

我尝试了什么:

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

1 个答案:

答案 0 :(得分:2)

这是一个完全可复制的示例,使用更好的方法添加自定义JavaScript,而不是使用额外代码重载linkDistance参数...

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