D3.js可观察的力布局,标签不出现 [英] D3.js Observable Force Layout, Labels not appearing

查看:30
本文介绍了D3.js可观察的力布局,标签不出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的

由于D3不支持z-index,因此添加元素的顺序显然是错误的.如何使标签出现在每个节点上?

解决方案

此处是更新的Observable.

问题是您在 circle 的内部"添加了文本,而这在SVG中是不可能的.解决方案是创建一个 group 而不是一个 circle ,使用 translate 代替 cx cy 标记,然后在 group 组内创建 circle text .希望对您有帮助.

My force layout code is standard, based of the usual data:

chart = {
  const links = data.links.map(d => Object.create(d));
  const nodes = data.nodes.map(d => Object.create(d));

  const simulation = d3.forceSimulation(nodes)
      .force("link", d3.forceLink(links).id(d => d.id))
      .force("charge", d3.forceManyBody())
      .force("center", d3.forceCenter(width / 2, height / 2))
      .force("link", d3.forceLink().distance(function(d) {return d.value;}).strength(0.1))

  const svg = d3.create("svg")
      .attr("viewBox", [0, 0, width, height]);

  const link = svg.append("g")
      .attr("stroke", "#999")
      .attr("stroke-opacity", 0.6)
    .selectAll("line")
    .data(links)
    .join("line")
      .attr("stroke-width", d => Math.sqrt(d.id));

  const node = svg.append("g")
      .attr("stroke", "#fff")
      .attr("stroke-width", 1.5)
      .attr("class", "labels")
    .selectAll("circle")
    .data(nodes)
    .join("circle")
      .attr("r", 10)
      .attr("fill", color)
      .call(drag(simulation));

  var lables = node.append("text")
      .text(function(d) {
        return d.id;
      })
      .attr('x', 6)
      .attr('y', 3);

  node.append("title")
      .text(d => d.id);

  simulation.on("tick", () => {
    link
        .attr("x1", d => d.source.x)
        .attr("y1", d => d.source.y)
        .attr("x2", d => d.target.x)
        .attr("y2", d => d.target.y);

    node
        .attr("cx", d => d.x)
        .attr("cy", d => d.y);
  });

  invalidation.then(() => simulation.stop());

  return svg.node();
}

I am trying to add labels to each node. Note the label code above. This adds the labels to the node element (confirmed by browser console), but the labels do not appear:

Since D3 doesn't support z-index the order of adding elements is obviously wrong. How can I make the labels appear on each node?

解决方案

Here is the updated Observable.

The problem was that you were adding the text "inside" the circle and that is not possible in an SVG. The solution is to create a group instead of a circle, use translate instead cx and cy in the tick function, and finally, create the circle and the text inside the group. I hope it helps.

这篇关于D3.js可观察的力布局,标签不出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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