【问题标题】:Force colliding labels but not their points in d3强制碰撞标签而不是它们在 d3 中的点
【发布时间】:2018-02-15 11:28:43
【问题描述】:

我正在使用 d3 制作一个必须支持多达 100 个点的折线图,因此非常拥挤。问题是一些标签重叠。

我尝试的方法涉及绘制所有点,然后分别绘制所有标签并在标签上运行强制碰撞以阻止它们重叠,然后在强制碰撞后在每个标签及其关联点之间绘制一条线.

我不能让力量发挥作用,更不用说画线了。

我们也热烈欢迎任何有关更好方法的建议。

这是我的代码:

$.each(data.responseJSON.responsedata, function(k, v) {
    var thispoint = svg.append("g").attr("transform", "translate("+pointx+","+pointy+")");
    thispoint.append("circle").attr("r", 10).style("fill","darkBlue").style("stroke","black");
    var label = svg.append("text").text(v.conceptName).style("text-anchor", "end").attr("font-family", "Calibri");
    label.attr("transform", "translate("+(pointx)+","+(pointy-12)+") rotate(90)")
    });
nodes = d3.selectAll("text")

simulation = d3.forceSimulation(nodes)
        .force("x", d3.forceX().strength(10))
        .force("y", d3.forceY().strength(10))
        .force("collide",d3.forceCollide(20).strength(5))
        .velocityDecay(0.15);

ticks = 0;

simulation.nodes(data)
    .on("tick", d => {
        ticks = ticks + 1;
        d3.select(this).attr("x", function(d) { return d.x }).attr("y", function(d) { return d.x });
        console.log("updated" + this)
    });

【问题讨论】:

  • "tick" 监听器中,如果您希望this 成为DOM 元素,请不要使用箭头函数。将其更改为常规函数。

标签: javascript d3.js


【解决方案1】:

强制布局是一种相对昂贵的移动标签以避免碰撞的方式。它是迭代和计算密集型的。

更高效的算法一次添加一个标签,确定每个标签的最佳位置。例如,“贪婪”策略按顺序添加每个标签,选择标签与已添加标签重叠最少的位置。

我创建了一个 D3 组件,d3fc-label-layout,它实现了许多标签布局策略:

https://github.com/d3fc/d3fc-label-layout

这是一个如何使用它的示例:

  // Use the text label component for each datapoint. This component renders both
  // a text label and a circle at the data-point origin. For this reason, we don't
  // need to use a scatter / point series.
  const labelPadding = 2;
  const textLabel = fc.layoutTextLabel()
    .padding(2)
    .value(d => d.language);

  // a strategy that combines simulated annealing with removal
  // of overlapping labels
  const strategy = fc.layoutRemoveOverlaps(fc.layoutGreedy());

  // create the layout that positions the labels
  const labels = fc.layoutLabel(strategy)
    .size((d, i, g) => {
      // measure the label and add the required padding
      const textSize = g[i].getElementsByTagName('text')[0].getBBox();
      return [
        textSize.width,
        textSize.height
      ];
    })
    .position((d) => {
      return [
        d.users,
                d.orgs
      ]
    })
    .component(textLabel);

https://bl.ocks.org/ColinEberhardt/27508a7c0832d6e8132a9d1d8aaf231c

【讨论】:

    猜你喜欢
    • 2013-07-29
    • 2011-10-18
    • 1970-01-01
    • 2017-08-27
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多