D3 circle pack - Adding labels to nodes

2.7k views Asked by At

While I've seen this question asked a few times, I'm having a bit trouble implementing. What I'd like to do is have the label attribute centered within each circle (as mentioned here). I believe I'd be adding the text attribute to:

canvas.selectAll('circles')
    .data(nodes)
    .enter()
    .append('svg:circle')
    .attr('cx', function (d) {
        return d.x;
    })
    .attr('cy', function (d) {
        return d.y;
    })
    .attr('r', function (d) {
        return d.r;
    })
    .attr('fill', function (d) {
        return d.color;
    });

But am confused on why the instructions they gave in the previous example I linked to doesn't work with the setup I currently have. I believe it's the pack option that could be throwing me off (about the difference between the two), but any further examples would be a huge help. Thanks!

Update

Thanks for the answers/suggestions, I updated the Codepen with my progress (as I needed two lines of data; should have clarified) which seems to be working well. Now this is packing into a circle - at the end of the day, I'd love for this to be packed in the actual #canvas width/height (which is a rectangle). I saw this treemap example - would that be what I'm going for here?

Demo of what I have so far

enter image description here

1

There are 1 answers

0
nrabinowitz On

Perhaps the confusion is that you can't add labels to the circle selection (because in SVG, a circle element can't contain a text element). You need to either make a g element that contains both circle and text, or a separate selection for the text, e.g.:

canvas.selectAll('text')
    .data(nodes)
    .enter()
    .append('svg:text')
    .attr('x', function (d) {
        return d.x;
    })
    .attr('y', function (d) {
        return d.y;
    })
    // sets the horizontal alignment to the middle
    .attr('text-anchor', "middle")
    // sets the vertical alignment to the middle of the line
    .attr('dy', '0.35em')
    .text(function(d) { 
      return d.label;
    });

See the updated demo: http://codepen.io/anon/pen/djebv