Constrained d3.js Force display

前端 未结 2 2027
难免孤独
难免孤独 2021-01-05 09:35

I\'d like to do something a little bit out of the ordinary with force layouts (for visualizing graphs). Constellations and all are fun to look at, but for timeseries data, i

2条回答
  •  北海茫月
    2021-01-05 10:18

    To elaborate on my comment, yes, this is perfectly possible. The force layout does not in fact position the nodes itself, it merely computes the positions. In the handler of the tick event you usually provide the function that takes care of the positioning. There, you can add arbitrary constraints that restrict how the nodes can move.

    Taking one of the stock examples, you could do things like the following to restrict the x coordinate to within +-10 of the intended position with unrestricted y.

    force.on("tick", function() {
      node.each(function(d) {
        var intended = scale(d.value);
        d.x = d.px = Math.min(intended + 10, Math.max(intended - 10, d.px));
      });
      node.attr("cx", function(d) { return d.x; })
          .attr("cy", function(d) { return d.y; });
    });
    

    Here is another example that uses the force layout to position labels. There, the x position is ignored (i.e. constant) and only the y is affected by the layout.

提交回复
热议问题