将圆放置在水平轴上,而不会使用力布局重叠 [英] Position circles on a horizontal axis without overlapping using force layout

查看:77
本文介绍了将圆放置在水平轴上,而不会使用力布局重叠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将圆放置在d3比例尺上,并以不重叠的方式使其松弛.我知道这会降低准确性,但是对于我要生成的图表类型来说,这是可以的.

I would like to position circles on a d3 scale and relax them in such a way that they do not overlap. I know that this decreases accuracy, but that's okay for the type of chart that I would like to generate.

这是我的最小(非)工作示例: https://jsfiddle.net/wmxh0gpb/1/

This is my minimum (non-)working example: https://jsfiddle.net/wmxh0gpb/1/

<body>
  <div id="content">
    <svg width="700" height="200">
      <g transform="translate(50, 100)"></g>
    </svg>
  </div>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"></script>

  <script>
var width = 600, height = 400;
var xScale = d3.scaleLinear().domain([0, 1]).range([0, 300]);

var numNodes = 5;
var nodes = d3.range(numNodes).map(function(d, i) {
  return {
    value: Math.random()
  }
});

var simulation = d3.forceSimulation(nodes)
  .force('x', d3.forceX().strength(0.5).x(function(d) {
    return xScale(d.value);
  }))
  .force('collision', d3.forceCollide().strength(1).radius(50))
  .on('tick', ticked);

function ticked() {
  var u = d3.select('svg g')
    .selectAll('circle')
    .data(nodes);

  u.enter()
    .append('circle')
    .attr('r', function(d) {
      return 25;
    })
    .style('fill', function(d) {
      return "black";
    })
    .merge(u)
    .attr('cx', function(d) {
      return d.x;
    })
    .attr('cy', function(d) {
      return 0
    })
    .attr("opacity", 0.5)

  u.exit().remove();
}
  </script>
</body>

使用forceX力对圆进行定位,并应使用forceCollide防止碰撞.但是,无论重叠如何,圆圈似乎都能找到一个稳定的位置,而不是避免它.

The circles are positioned using the forceX force and collision should be prevented using forceCollide. However, the circles seem to find a stable position regardless of the overlap instead of avoiding it.

我在做什么错了?

推荐答案

因为您忽略了力模拟的y坐标

Because you ignore the y coord of the force simulation

将其添加为tick函数的最后一行.现在,您强制节点位于y == 0

Add this as the last line of the tick function. Now you force the nodes to be at y==0

nodes.forEach(e => { e.fy = 0 });

并将碰撞力的半径设置为实际半径(25)

And set the radius of the collision force to the real radius (25)

.force('collision', d3.forceCollide().strength(1).radius(25))

这篇关于将圆放置在水平轴上,而不会使用力布局重叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆