Kerrin631
Kerrin631

Reputation: 198

How do I change the position of a circle svg element using the transform attribute?

I am currently building a sunburst chart in D3JS and am trying to append circles to each node. You can view current project here: https://jsfiddle.net/mhxuo260/.

I am trying to position each of the circles in the top right hand corner of their respective node. Currently they will only position in the center which covers the node labels. I have been scouring the net in search for a clue but just haven't come up with anything yet. Any suggestion would be appreciated.

d3.json("flare.json", function(error, root) {
if (error) throw error;

var g = svg.selectAll("g")
    .data(partition.nodes(root))
    .enter().append("g");

path = g.append("path")
    .attr("d", arc)
    .attr('stroke', 'white')
    .attr("fill", function(d) { return color((d.children ? d : d.parent).name); })
    .on("click", magnify)
    .each(stash);

var text = g.append("text")
    // .attr("x", function(d) { return d.x; })
    // .attr("dx", "6") // margin
    // .attr("dy", ".35em") // vertical-align
    .text(function(d) {
        return d.name;
    })
    .attr('font-size', function(d) {
        return '10px';
    })
    .attr("text-anchor", "middle")
    .attr("transform", function(d) {
        if (d.depth > 0) {
            return "translate(" + arc.centroid(d) + ")" +
                   "rotate(" + getStartAngle(d) + ")";
        } else {
            return null;
        }
    })
    .on("click", magnify);

var circle = g.append('circle')
    .attr('cx', function(d) { return d.x })
    .attr('cy', function(d) { return d.dy; })
    .attr('r', '10')
    .attr('fill', 'white')
    .attr('stroke', 'lightblue')
    .attr("transform", function(d) {
        console.log(arc.centroid(d))
        if (d.depth > 0) {
            return "translate(" + arc.centroid(d) + ")" +
                   "rotate(" + getStartAngle(d) + ")";
        } else {
            return null;
        }
    });

Upvotes: 0

Views: 1011

Answers (1)

Matthew Wilcoxson
Matthew Wilcoxson

Reputation: 3622

You are using the ´´´arc.centroid´´´ function which always returns the x,y midpoint of the arc. All that function is doing is:

The midpoint is defined as (startAngle + endAngle) / 2 and (innerRadius + outerRadius) / 2

You just need to calculate a different position using these values depending on where you want it. Use the transform like this (sudo code):

.attr( "transform", function(d) {
        var x = (startAngle + endAngle) / 2;
        var y = (innerRadius + outerRadius) / 2;

        return "translate(" + x +"," + y + ")";
    });

You don't need to rotate your circle.

(FYI: javascript will convert arrays into strings by joining each number with commas, this is why arc.centroid returning an array works here)

Upvotes: 1

Related Questions