vasturiano / react-force-graph

React component for 2D, 3D, VR and AR force directed graphs
https://vasturiano.github.io/react-force-graph/example/large-graph/
MIT License
2.2k stars 284 forks source link

how to get a graph with less spacing? #510

Open dcsan opened 5 months ago

dcsan commented 5 months ago

I have some graphs that end up looking like the below. are there any parameters to draw the force-graph nodes tighter together, especially for un-connected nodes?

image

I can't just make the nodes bigger as that will create overlaps on connected items.

image

vasturiano commented 5 months ago

@dcsan one thing that you can try is set a maximum distance for the repelling force that acts between every pair of nodes. This force has the intent of spreading the graph out, but when you have disconnected groups it can cause them to drift apart. Setting a max distance of influence can counter act this. You need to calibrate the many-body d3Force.

Something like:

myGraphRef.current.d3Force('charge').distanceMax(100); // adjust to taste
dcsan commented 5 months ago

@vasturiano thanks for the tip! I didn't know it was possible to reach in and modify the d3Force in that way.

For others coming by you need these bits.

  const graphRef = useRef<any>(null);

  useEffect(() => {
    graphRef?.current?.d3Force('charge').distanceMax(40); // adjust to taste
  }, [])

  // then in the graph component
  return (
      <ForceGraph2D
        ref={graphRef}

I was thinking I might be able to modify other props. eg gravity https://gist.github.com/sathomas/1ca23ee9588580d768aa#file-index-html-L163 but can't figure out the syntax to access.

// works:
graphRef?.current?.d3Force('charge').distanceMax(40); 

// works with a glitch
setTimeout(() => {
      graphRef?.current?.zoomToFit();
}, 500) 

// doesn't work!
graphRef?.current?.d3Force('gravity').strength(0.1); 

tried various permutations and digging into the source to try and see how to set this:

also the client side debugger

image

-> it maybe worth turning this into a discussion as having access to the d3 settings opens a lot of other possibilities!

vasturiano commented 5 months ago

@dcsan there is no force called "gravity" by default in the system. The only 3 forces active by default are "charge", "link" and "center". You can read a bit more about it in the docs here: https://github.com/vasturiano/react-force-graph?tab=readme-ov-file#force-engine-configuration