Pixelord
Pixelord

Reputation: 641

D3.JS, How can I render multiple objects in the same data binding?

I have a data model which is an array of object with start time and end time. Now I want to render gantt chart type cart with it.

It is easy to bind data and render a single line with it:

chart.data(myDataList).enter().append("line")
                              .attr("x1", function(d){return d.x})
                              .attr("y1", lineHeight)
                              .attr("x2", function(d){return d.y})
                              .attr("y2", lineHeight)

The data could be like

myDataList = [ [start time, end time], 
               [start time 2, end time 2],
               [start time 3, end time 3]]

Now I need to render something like this with each data item:

O-------------------O

That is addition to the line, there will be circle in both end of the line. Circle cx data will be coming from d.x and d.y. However, I am not quite sure how to bind the same data element in three elements.

Any help?

Upvotes: 1

Views: 1151

Answers (2)

Cyril Cherian
Cyril Cherian

Reputation: 32327

First you make the line:

chart.data(myDataList).enter().append("line")
                              .attr("x1", function(d){return d.x})
                              .attr("y1", lineHeight)
                              .attr("x2", function(d){return d.y})
                              .attr("y2", lineHeight)

now make circles

//make inner circle
chart.selectAll(".in").data(dataset).enter()
  .append("circle")
   .attr("class", "in")
  .attr("cx", function(d) {
    return xScale(d[0])
  })
  .attr("cy", function(d) {
    return xScale(d[0])
  })
  .attr("r", 2); 
  //make outer circle      
  chart.selectAll(".out").data(dataset).enter()
  .append("circle")
  .attr("class", "out")
  .attr("cx", function(d) {
    return xScale(d[1])
  })
  .attr("cy", function(d) {
    return xScale(d[0])
  })
  .attr("r", 2); 

Working code here

Upvotes: 2

Harish
Harish

Reputation: 119

First,cache the line code in a variable.

 var line=chart.data(myDataList).enter().append("line")
.attr("x1", function(d){return d.x}) 
.attr("y1", lineHeight) 
.attr("x2", function(d){return d.y}) 
.attr("y2", lineHeight)

Then,now using the variable,we can add circles using the same data element as

line.append("circle") 
.attr("cx", function(d){return d.x}) 
.attr("cy", lineHeight)
.attr("r", 4);//First circle

now,the second circle ...

line.append("circle") 
.attr("cx", function(d){return d.y}) 
.attr("cy", lineHeight) 
.attr("r", 4);//Second circle

Upvotes: 0

Related Questions