Alan
Alan

Reputation: 46903

Adding svg:circle elements to a d3.js line

I'm rendering a line chart via d3, which is bound to an array of objects of the following format:

{ name: "somename",
  pointStart: 90210, 
  pointInterval: 187, 
  data: [1,2,3,4,5]
}

The Y values are the values in data, and the X values is a sequence of Date values, calculated by adding pointStart to the product of pointInterval and the index of data

In addition to plotting the line path, I'm trying to overlay "circles" at each x,y coordinate. The line renders properly, and all but the first circle shows up.

Check this plunkr for the live example.

Since the line path already has the x,y coordinates, I was hoping to use that, and draw the circle on each pair, however the first circle coordinate isn't found and I'm not sure why.

This is the code that selects the line array, gets the x,y pairs, and then draws the circle. The data is bound to a 9 element array, but only 8 circles are added to the dom...

lines.selectAll('path')
.data(function(d) { console.log(getDataArray(d)); return getDataArray(d); })
.enter()
.append('circle')
.attr({
    class:'dot',
    cx:line.x(),
    cy:line.y(),
    r:circleR,
    fill: function(d,i,e) { return colors(data[e].name);}
})

Upvotes: 1

Views: 1046

Answers (1)

Scott Cameron
Scott Cameron

Reputation: 5333

It's because you're selection for "path" but adding "circles". When you do lines.selectAll('path') it returns a selection that contains 1 element because there is already a <path> element under lines. So when you do the data bind with 9 elements, the first element get bound to the existing path leaving the remaining 8 elements for the enter selection.

If you change it to this it should work:

lines.selectAll('circle')
    .data(function(d) { console.log(getDataArray(d)); return getDataArray(d); })
    .enter()
    .append('circle')

Upvotes: 4

Related Questions