Joey Orlando
Joey Orlando

Reputation: 1432

SVG line out of arc starting position - d3.js

I'm trying to achieve this enter image description here

but this is currently what I have enter image description here Essentially all I need to do is figure out how to have the lines emanating out from the circle starting at the arc start.

My question is exactly that, how can I translate the arc starting position into the x1,y1 attribute of an svg line. Below is the code that I currently have pertaining to drawing the lines:

// Draw lines emanating out
g.append('line')
    .attr('class', 'outer-line')
    .attr('x1', function(d) {
        return 0;
    })
    .attr('x2', 0)
    .attr('y1', -radius)
    .attr('y2', -radius-150)
    .attr('stroke', function(d, i) {
        return color(i); 
    })
    .attr('stroke-width','2')
    .attr("transform", function(d) {
        return "rotate(" + (d.startAngle+d.endAngle)/2 * (180/Math.PI) + ")";
    });

Upvotes: 4

Views: 1390

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102194

If I understand your problem correctly, you can use just d.startAngle:

g.attr("transform", function(d) {
    return "rotate(" + d.startAngle * (180/Math.PI) + ")";
});

Check here an example (click on "run code snippet"):

var dataset = [300, 200, 400, 200, 300, 100, 50];

var width = 460,
    height = 300,
    radius = Math.min(width, height) / 2;

var color = d3.scale.category20();

var pie = d3.layout.pie()
    .sort(null);

var arc = d3.svg.arc()
    .innerRadius(radius - 100)
    .outerRadius(radius - 50);

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)
    .append("g")
    .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

var path = svg.selectAll("path")
    .data(pie(dataset))
  .enter().append("path")
    .attr("fill", function(d, i) { return color(i); })
    .attr("d", arc);
    
var g = svg.selectAll(".groups")
  .data(pie(dataset))
  .enter()
  .append("g");
  
  g.append('line')
    .attr('class', 'outer-line')
    .attr('x1', 0)
    .attr('x2', 0)
    .attr('y1', -radius + 50)
    .attr('y2', -radius)
    .attr('stroke', 'black')
    .attr('stroke-width','2')
    .attr("transform", function(d) {
        return "rotate(" + d.startAngle * (180/Math.PI) + ")";
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

Upvotes: 4

Related Questions