5

I am trying to make some adjustments to a network graph plotted using forcenetwork in R.

In particular, I would like to change the text label colour to black (or white, for black background) and bring the text labels to the front of the nodes. The standard option makes it really difficult to read the text labels as some labels are too light in colour, while others are obstructed by dense clusters of nodes.

It would be nice if I can change the legend text colour too, so that I can have the flexibility to change the background colour.

One possible solution as pointed out in this post here, is to hijack some unused parameters.

forceNetwork(Links = MisLinks, Nodes = MisNodes,
   Source = "source", Target = "target",
   Value = "value", NodeID = "name",
   Group = "group", opacity = 0.8,
   linkDistance = 
     JS('function(){d3.select("body").style("background-color", "#DAE3F9");return 50;}'))

However, with no knowledge in JS, I have no idea how to write it or whether it is even possible.

CJ Yetman
  • 8,373
  • 2
  • 24
  • 56
Seamus Lam
  • 155
  • 3
  • 10
  • The `forceNetwork` is designed with using different node colours in mind (like communities), if you want to recolour all nodes in white just use `simpleNetwork` – JohnCoene Apr 27 '16 at 06:19
  • I am not trying to recolour the nodes. I am trying to detach the node colour and label colour. Specifically, I want the node to retain its group-specific colour while changing all text label colour to black. – Seamus Lam Apr 27 '16 at 06:36
  • I managed to change the legend text color and label text colour by messing around with the forceNetwork.js file in the networkD3 library. Anyone know if it is possible to bring text label infront of the node? – Seamus Lam Apr 28 '16 at 03:51
  • @SeamusLam can you post your solution for coloring the labels? – rrs May 18 '16 at 15:58
  • @rrs my answer below provides one way to set the label text color – CJ Yetman May 25 '17 at 12:35

1 Answers1

2

You can add custom CSS to set the background color, color the legend text, and color the node label text using the package. Changing the z-order of the text labels would be much more complicated because you have to reorder elements inside the SVG, and I'm not sure that would even be worth it.

library(networkD3)
library(htmltools)

browsable(
  tagList(
    tags$head(
      tags$style('
        body{background-color: #DAE3F9 !important}
        .nodetext{fill: #000000}
        .legend text{fill: #FF0000}
      ')
    ),
    forceNetwork(Links = MisLinks, Nodes = MisNodes,
                 Source = "source", Target = "target",
                 Value = "value", NodeID = "name",
                 Group = "group", opacityNoHover = 1, 
                 fontSize = 12, legend = T, zoom = T)
  )
)
CJ Yetman
  • 8,373
  • 2
  • 24
  • 56