[英]How to append a circle to each point of each valueline in d3js?
我從具有嵌套數據的對象數組創建了一個多折線圖,但是圓圈僅附加到 1 行。 我在前端使用 react 並從 rest api 獲取數據,如圖所示示例線條已創建,圓圈上的工具提示正常工作,但只有一行附加了圓圈。
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);
});
嘗試下面的更改,注意使用迭代器來區分每行的類/點選擇。 您可以使用其他內容,例如數據的屬性,例如名稱等。
我也沒有將 line 和 color scale 函數移出forEach
循環,因為它們不需要多次聲明。 這同樣適用於您的工具提示,它可以重用而不是向 DOM 添加多個 div。
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));
var div = d3.select("body").append("div")
.attr("class", "tooltip")
.style("opacity", 0);
Object.values(data).forEach((item,k) => {
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
svg
.selectAll(".dot-"+k)
.data(item.results)
.enter()
.append("circle") // Uses the enter().append() method
.attr("class", "dot-"+k)
.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);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.