【问题标题】:Using a Different Naming Convention for Links in D3在 D3 中为链接使用不同的命名约定
【发布时间】:2015-05-04 14:00:58
【问题描述】:

是否可以更改 D3 中的“链接”?我从服务器收到的 JSON 设置为“节点”和“边缘”,而不是“节点”和“链接”。这是一个示例 JSON:

{
"nodes": [
{"fixed":true,"data": {"id": "foo","idType":"USERNAME","color":"red"},"selected":false},
{"fixed":true,"data": {"id": "bar","idType":"USERNAME","color":"yellow"},"selected": false}
],
"edges": [
{"classes":null,"data":{"color":"blue","source":"foo","target":"bar","visible":true},"grabbable":false},
{"classes":null,"data":{"color":"green","source":"bar","target":"foo","visible":true},"grabbable":false}
]}

一开始我以为是从

声明的
var link = svg.selectAll(".link"),
    node = svg.selectAll(".node");

但是,当我将 .link 更改为 .edge 时,我的代码会中断。

// sets the source and target to use id instead of index
var edges = [];
root.edges.forEach(function(e) {
    var sourceNode = root.nodes.filter(function(n) {
                return n.data.id === e.data.source;
            })[0],
            targetNode = root.nodes.filter(function(n) {
                return n.data.id === e.data.target;
            })[0];

    // push the attributes in the JSON to the edges.
    edges.push({
        source: sourceNode,
        target: targetNode,
        label: e.data['label'],
        color: e.data['color']
    });
});

force
        .nodes(root.nodes)
        .links(edges)
        .start();

link = link
        .data(edges)
        .enter().append("line")
        .attr("class", "link")
        .style("stroke-width", 1.5);

node = node
        .data(root.nodes)
        .enter().append("g")
        .attr("class", "node");

【问题讨论】:

  • 我认为 d3 怎么称呼它并不重要。你如何初始化你的图表?
  • 我会用代码更新我的问题。有点长。

标签: javascript json d3.js force-layout


【解决方案1】:

Halcyon 关于 d3 不关心你所说的 links 的评论让我意识到我的代码并没有脱离图形的实际初始化。它打破了我使用id 作为source/target 而不是默认的index 的方式。

root.links.forEach... 更改为root.edges.forEach... 解决了这个问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-28
    • 2020-11-06
    • 1970-01-01
    相关资源
    最近更新 更多