【问题标题】:D3 network chart: add textD3 网络图:添加文字
【发布时间】:2017-06-16 11:52:38
【问题描述】:

我需要将文本标签添加到此 D3 力导向图表(来自 Zoomable Force Directed Graph d3v4 link)。 但是,我不明白向圆圈和链接添加标签所需的编辑。节点标签是属性“node.label”,边缘标签是属性“edge.label”。 这个d3 Node Labeling 解释了所需的编辑,但我无法让它工作(不幸的是,我不是 JS 程序员)。如何编辑它以便可以为节点添加属性“node.label”,并将属性“edge.label”添加到边缘?

//add encompassing group for the zoom
var g = svg.append("g")
    .attr("class", "everything");

//draw lines for the links
var link = g.append("g")
    .attr("class", "links")
    .selectAll("line")
    .data(links_data)
    .enter().append("line")
    .attr("stroke-width", 2)
    .style("stroke", linkColour);

//draw circles for the nodes
var node = g.append("g")
        .attr("class", "nodes")
        .selectAll("circle")
        .data(nodes_data)
        .enter()
        .append("circle")
        .attr("r", radius)
        .attr("fill", circleColour);

【问题讨论】:

    标签: d3.js


    【解决方案1】:

    你可以做的是让你的节点变成一个而不是一个圆圈,给它添加一个文本。您还必须更改 tickActions 函数,使其移动 :

    绘制节点为 g:

    var node = g.append("g")
            .attr("class", "nodes")
            .selectAll(".node")
            .data(nodes_data)
            .enter()
            .append("g")
            .attr("class","node")
            .each(function(d){
                d3.select(this)
                        .append("circle")
                        .attr("r", radius)
                        .attr("fill", circleColour(d));
                d3.select(this)
                        .append("text").text(d.name)
                        .attr("dy",radius+10)
                        .style("text-anchor","middle");
            });
    

    勾选功能:

    function tickActions() {
        //update node positions each tick of the simulation
        node
                .attr("transform", function(d) { return "translate("+d.x+","+ d.y+")"; });
    
        //update link positions
        link
                .attr("x1", function(d) { return d.source.x; })
                .attr("y1", function(d) { return d.source.y; })
                .attr("x2", function(d) { return d.target.x; })
                .attr("y2", function(d) { return d.target.y; });
    }
    

    【讨论】:

    • 我使用 d.name 作为节点,但您可以使用您的数据集属性。你可以对链接做同样的事情。但你明白了。
    猜你喜欢
    • 1970-01-01
    • 2023-03-03
    • 2018-02-07
    • 2022-01-07
    • 1970-01-01
    • 2020-10-20
    • 2014-11-25
    • 2020-10-09
    • 2017-04-07
    相关资源
    最近更新 更多