D3.js Venn Diagram Text Labels

974 views Asked by At

I am using this great example to create Venn diagrams: http://bl.ocks.org/christophe-g/b6c3135cc492e9352797

I am currently trying to put text labels on all the nodes (the small circles) but since I am new to the D3.js library I am struggling to get this done. I managed to assign a text label to all the nodes (this can been seen by inspecting the HTML code with e.g. Firebug), however the text label does not show up. How can I put a visible text label on the nodes?

A fiddle with the code in which the text labels don't show up on the nodes can be found below:

 /* Create the text for each individual circle */
    pointsEnter.append("text")
    .attr("class", "label")
    .attr("text-anchor", "middle")
    .attr("dy", ".40em")

    pointsEnter.selectAll("text.label").data(function(d) {
        return [d];
    })
    .text(function(d) {
        return d.name;
    })
    .attr("x", function(d) {
        return d.x
    })
    .attr("y", function(d) {
        return d.y
    });

https://jsfiddle.net/ej5uz83n/1/

Any help is greatly appreciated.

1

There are 1 answers

0
Mark On BEST ANSWER

Right now you are attempting to append a text element to a circle, you can't do this in SVG. The easiest way to fix it is to append a g element for each circle/text pair and then position them together with a transform:

var points = circleContainer.selectAll("circle.node")
  .data(function(d) {
    return d.nodes
  }, function(d) {
    return d.name
  });      

// group for circle and text
var g = points.enter().append("g");

g.append('circle')
  .attr('r', 0)
  .attr('class', 'node')
  .call(layout.packer().drag);

/* Create the text for each individual circle */
g.append("text")
  .attr("class", "label")
  .attr("text-anchor", "middle")
  .attr("dy", ".40em")
  .text(function(d){
    return d.name;
    })
  .style("fill", "black");  

g.selectAll("circle").transition()
  .duration(isFirstLayout ? 0 : test.duration())
  .attr('r', function(d) {
    return d.r
  });

points.exit().transition()
  .attr('r', 0)
  .remove();

The "ticker" function then becomes:

ticker: function() {
  g.attr("transform", function(d) {
    return "translate(" + d.x + "," + d.y + ")";
  })
}

Updated fiddle.