简体   繁体   中英

Labeling force-directed nodes in d3: speed vs visibility

Yet another question about adding labels to a d3 force graph...

I am labeling a graph with nodes that are inside individual groups, and I have been appending the labels inside these groups like so:

<svg>
  <g class="nodes-with-labels">
    <g class="individual-node">
      <circle></circle>
      <text>Node Label</text>
    </g>
    ...
  </g>
</svg>

This adds minimal extra elements to the graph and allows my graph's tick() function to just call one transform operation. I put up a demo fiddle here (without any movement/ tick() function): https://jsfiddle.net/52cLjxt4/1/

Unfortunately, the labels end up behind many of the nodes because they are in groups that are drawn before other groups that contain nodes. This problem can be solved by putting nodes and labels into separate parent groups, like in this example :

https://jsfiddle.net/hhwawm84/1/

<svg>
  <g class="nodes">
    <g class="individual-node">
      <circle></circle>
    </g>
    ...
  </g>
  <g class="labels">
    <g class="individual-label">
      <text>Node Label</text>
    </g>
    ...
  </g>
</svg>

However, this appears to be significantly slower: it creates more elements and requires two transform statements instead of one in the tick() statement, since it's moving the labels around separately.

Speed is a real concern for my project. Is there a better approach here that might avoid creating so many extra groups and doubling the transform statements?

You don't need to each label and circle in an g - just set the transform attribute directly on each element. It might also be worth profiling setting the cx / cy and x / y attributes instead of transform too.

If you don't need the graph to animate, precomputing the ticks and setting the transforms could help with performance:

for (var i = 0; i < 120; ++i) simulation.tick();

If that's still too slow, try using canvas (faster because it doesn't have a scene graph) or css transforms on html elements (faster because they are gpu accelerated ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM