user1788720
user1788720

Reputation: 327

Add/update labels to a d3.js graph

I'm new to d3.js, and I struggle with the syntax.

I usually know how to add labels to a graph... but not with this code (which I have taken from D3.js Force Layout - showing only part of a graph )

I have tried the various solutions [ .append("text"), enter().append("text")....] but I have been unsuccessful.

Here is the part of the code where I think that I have to change something (and, below the code, you'll find a gihub repo of the entire thing)

        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

Upvotes: 0

Views: 896

Answers (1)

Lars Kotthoff
Lars Kotthoff

Reputation: 109242

To append multiple sets of elements for one .enter() selection, you need to access it several times. It's usually a good idea to group sets of elements.

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(...);

Upvotes: 1

Related Questions