Home > Software design >  Draw line with d3js with .data()
Draw line with d3js with .data()

Time:05-17

I want to draw 2 lines from a data set like this lineData = [{"x":57,"y":416},{"x":449,"y":30},{"x":977,"y":519},{"x":913,"y":53}] line 1 {"x":57,"y":416},{"x":449,"y":30} and line 2 {"x":977,"y":519},{"x":913,"y":53} with this code

lineData = [{"x":57,"y":416},{"x":449,"y":30},{"x":977,"y":519},{"x":913,"y":53}
     svgGroup
                .selectAll("line")
                .data(lineData)
                .enter()
                .append("line")
                .attr("x1", cData[0].x)
                .attr("x2", cData[1].x)
                .attr("y1", cData[0].y)
                .attr("y2", cData[1].y)

As a result, I got 4 identical lines. Is it possible to draw only 2 lines with data() or do I need to transform the lineData array before using in .data() function? Thanks

CodePudding user response:

You need do a little transform work before data binding:

let rawData = [
  {"x":57,"y":416},{"x":449,"y":30}, // lineA
  {"x":977,"y":519},{"x":913,"y":53} // lineB
],
    
    //  [lineA, lineB] -> [[pointA1, pointA2], [pointB1, pointB2]]
    transformData = [[rawData[0], rawData[1]], [rawData[2], rawData[3]]]; 


d3.select("#container")
  .selectAll("line")
  .data(transformData)
  .enter()
  .append("line")
  .attr("x1", d => d[0].x) // d  -> line -> [point1, point2]
  .attr("x2", d => d[0].y)
  .attr("y1", d => d[1].x)
  .attr("y2", d => d[0].y)
  .attr("stroke", 'blue')
  .attr("stroke-width", 1);

  • Related