0

我是 d3.js 的新手,我在语法上很挣扎。

我通常知道如何向图表添加标签......但不知道这段代码(我取自D3.js Force Layout - 只显示图表的一部分

我尝试了各种解决方案 [ .append("text"), enter().append("text")....] 但我没有成功。

这是我认为我必须更改某些内容的代码部分(并且,在代码下方,您会找到整个事情的 gihub 存储库)

        this.link = this.link.data(this.force.links(), function (d) {

            return d.source.id + "-" + d.target.id;
        });

        this.link.enter().insert("line", ".node").attr("class", "link")

            .style("opacity", 0)
            .transition().duration(1000)

            .style("opacity", 1);

        this.link.exit()
            .remove();



        this.node = this.node.data(this.force.nodes(), function (d) {
            return d.id;

        });

        if (this.node.enter().empty()==false ||this.node.exit().empty() == false) {
            transition = true;
        }


        this.node.enter()
            .append("circle")
            .style("opacity", 1)
            .attr("class", "node")
            .style("fill", function (d) {
                return d.color;
            })
            .attr("r", 18)
            /*.on('mouseover', this.mouseOver)*/
            .on('mousedown', this.mouseDown)
            .on('mouseout', this.mouseOut)
            .on("dragstart", this.dragStart)
            .on("click", this.click)
            .call(this.nodeDrag)
            .transition().duration(1000)
            .style("opacity", 1)
            .each("end",function(){transition=false;});


        this.node.each(function(d) {
            if (d.centerNode==false) {
              this.setAttribute('r',12);
            } else if (firstRound) {
                this.setAttribute('r',30);
                firstRound  =false;
            }
        });





        this.node.exit().transition().duration(1000).style("opacity", 0)
            .each("end",function(){transition=false;})
            .remove();

https://github.com/coulmont/pornograph

4

1 回答 1

1

要为一个选择附加多组元素.enter(),您需要多次访问它。对元素集进行分组通常是个好主意。

var gs = this.node.enter().append("g");
gs.append("circle")
        .style("opacity", 1)
        .attr("class", "node")
        .style("fill", function (d) {
            return d.color;
        }) // etc
gs.append("text")
  .style("text-anchor", "center")
  .text(...);
于 2014-02-07T11:39:31.033 回答