Question

Hey guys I recently started learning D3.js and have ran into a problem: http://i.stack.imgur.com/Nqghl.png. How can I stop drawing the line at the outer edge of these circles?

Possibly another solution could be to re-arrange the layers so that the circle one is on top of the line one.

Here is my sample code

data = [{name: 'one', parent: 'one', a: 1}, {name: 'two', parent: 'one', a: 2}, {name: 'three', parent: 'one', a: 2}]
  r = 30;
  var centerX = function (d, i) {
    return (i * ((r * 2) + 20)) + r;
  };

  var centerY = function (a, i) {

    return (a * 160) + (r * 2);
  }
  var global = d3.select('body')
    .append('svg')
    .attr('width', 500)
    .attr('height', 500)  

  global.selectAll("circle")
    .data(data)
    .enter()
      .append("circle")
      .style("stroke", "gray")
      .style("fill", "aliceblue")
      .attr('r', r)
      .attr('cx', function(d, i ) {return centerX(r, i)})
      .attr('cy', function(d, i) {return centerY(d.a, i)})
      .attr('id', function(d) { return 'one'});

  global.selectAll("line")
    .data(data)
    .enter()
      .append("line")
      .style("stroke", "rgb(6,120,155)")
      .style("stroke-width", 4)
      .style('stroke-opacity', .4)
      .attr('x1', function(d, i) {return centerX(r, i)})
      .attr('y1', function(d, i) {return centerY(d.a, i)})
      .attr('x2', function(d) {
        var selector = "[id="+d.parent+"]";
        return global.select(selector).attr('cx');
      })
      .attr('y2', function(d) {
        var selector = "[id="+d.parent+"]";
        return global.select(selector).attr('cy');
      })

Any ideas? Thanks in advance!

Was it helpful?

Solution

You are right about switching the order in which you append the lines and circles, lines first, then circles. You just have to be careful to preserve the line selection in a variable that you can use to apply the line attributes that are dependent on the circles AFTER drawing the circles.

FIDDLE example

lines
  .attr('x2', function(d) {
    var selector = "[id="+d.parent+"]";
    return global.select(selector).attr('cx');
  })
  .attr('y2', function(d) {
    var selector = "[id="+d.parent+"]";
    return global.select(selector).attr('cy');
  });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top