使用 d3js 和 .data() 画线
Draw line with d3js with .data()
我想从这样的数据集中画出 2 条线
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);
我想从这样的数据集中画出 2 条线
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);