我想从这样的数据集中画两条线lineData = [{"x":57,"y":416},{"x":449,"y":30},{"x":977,"y":519},{"x":913,"y":53}]
1号线{"x" 57岁的"y": 416},{"x" 449年,"y": 30}和第2行{"x" 977年,"y": 519},{"x" 913年,"y": 53}使用下面的代码
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)
结果,我得到了4条相同的行。是否有可能仅用data()绘制2行,或者我是否需要在.data()函数中使用之前转换lineData数组?由于
您需要在数据绑定之前做一些转换工作:
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);