Search code examples
javascriptd3.jsnetwork-programmingscalereverse

How to reverse linear scale for d3?


I am attempting to create a network in which the highest weighted edges have the smallest distances in between their associated nodes. I attempted the clunky way as shown below of simply giving the "minimum" output in the range, the highest real input and doing the reverse for the "maximum" output.

However, this did not completely work. While no errors were thrown and a visualization was drawn, there were still some edges with lower weights that had smaller distances than those with higher weights. Is there a better way to reverse the outputs of my linear scale? Or is this problem occurring because of something different in my code?

var distance_scale = d3.scale.linear()
  .domain([min, max])
  .range([max * 0.0015, min * 0.0015]);
var svg = d3.select("body")
  .append("svg")
  .attr("width", w)
  .attr("height", h);
var force = d3.layout.force()
  .links(data.edges)
  .nodes(data.nodes)
  .size([w, h])
  .linkDistance(function(d) {
    return distance_scale(d.weight)
  })
  .charge([-1000])
  .start();
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>


Solution

  • The link distance in the force layout is only a guideline. There's no way to enforce a specific length for a specific link.