【发布时间】:2020-06-11 20:10:05
【问题描述】:
我从一组包含嵌套数据的对象创建了一个多线图,但是这些圆圈仅附加到 1 行。我在前端使用 react 并从 rest api 获取数据,如图所示Example 线条被创建并且圆圈上的工具提示正常工作,但只有一行附加了圆圈。
Object.values(data).forEach(item => {
var valueline = d3
.line()
.x(function(d) {
return x(d.circuit);
})
.y(function(d) {
return y(+d.points);
});
var colorScale = d3
.scaleSequential(interpolateRainbow) //.scaleSequential(d3.interpolateRainbow)
.domain([1, 20]);
console.log(colorScale(1));
svg
.append("path")
.data([item.results])
.attr("class", "line")
.style("stroke", colorScale(item.constructor))
.attr("d", valueline);
var xScale = d3
.scaleLinear()
.domain([0, item.results.length-1]) // input
.range([0, width]); // output
var div = d3.select("body").append("div")
.attr("class", "tooltip")
.style("opacity", 0);
svg
.selectAll(".dot")
.data(item.results)
.enter()
.append("circle") // Uses the enter().append() method
.attr("class", "dot")
.attr("r", 5) // Assign a class for styling
.attr("cx", function(d, i) {
return xScale(i);
})
.attr("cy", function(d, i) {
return y(d.points);
}).on("mouseover", function(d) {
let points = item.results.filter(xd => xd.circuit==d.circuit)[0].points
div.transition()
.duration(200)
.style("opacity", .9);
div .html(item.name + "<br/>" + points)
.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY - 28) + "px");
})
.on("mouseout", function(d) {
div.transition()
.duration(500)
.style("opacity", 0);
});
【问题讨论】:
-
嘿西蒙,试着区分你的点的类别。我猜唯一带点的行是 forEach 循环中的最后一行,因为您选择了所有点并将最后一个 item.results 附加为数据。在 forEach 循环中添加一个迭代器并执行类似 .attr("class", "dot-" + i) 之类的操作,当您 selectAll 时,还要执行 .selectAll("dot-" + i)。希望这会有所帮助。
-
是的,这就是问题所在。谢谢。
标签: javascript arrays reactjs d3.js charts