【发布时间】:2018-12-30 23:39:21
【问题描述】:
我有一个用d3 制作的折线图,但由于数据的形状,线和点(我在每个特定数据点的线上使用点)通常最终会相互重叠.
为了解决这个问题,我结束了对线条和点的不透明度0.4,当您将鼠标悬停在一条线上时,该特定数据行的线条和点会弹出,并将其不透明度设置为1 .
我的问题是:我正在使用 .raise() 函数使它们弹出并站在其余的线条和点上,该功能仅适用于我的线条选择而不是我的点选择,我不知道为什么。
我的代码:
// draw the data lines
const lines = svg.selectAll('.line')
.data(this.data)
.enter()
.append('path')
.attr('class', 'data.line')
.attr("fill", "none")
.attr("stroke", d => colors(d.key))
.attr("stroke-linejoin", "round")
.attr("stroke-linecap", "round")
.attr("stroke-width", 2.5)
.attr('stroke-opacity', 0.4)
.attr('d', d => line(d.values))
.on('mouseenter', d => {
// Highlight them
let myCircles = circles.selectAll('.circle');
lines.attr('stroke-opacity', b => {
return b.key === d.key ? 1 : 0.4;
});
myCircles.attr('fill-opacity', b => {
return b[this.typeIdentifier] === d.key ? 1 : 0.4;
});
// Bring them to the front
myCircles = circles.selectAll('.circle')
.filter(b => b[this.typeIdentifier] === d.key);
const myLines = lines.filter(b => b.key === d.key);
myLines.raise();
myCircles.raise();
});
// draw the circles
const circles = svg.selectAll('.circle')
.data(this.data)
.enter()
.append('g');
circles.selectAll('.circle')
.data(d => d.values)
.enter()
.append('circle')
.attr('class', 'circle')
.attr('stroke', 'white')
.attr('stroke-width', 1)
.attr('r', 6)
.attr('fill', d => colors(d[this.typeIdentifier]))
.attr('fill-opacity', 0.4)
.attr('cx', d => x(d[this.xAxisValue]) + x.bandwidth() / 2)
.attr('cy', d => y(d[this.yAxisValue]))
.on('mouseenter', (d, b, j) => {
tooltip.raise();
tooltip.style("display", null);
tooltip.select("#text1").text(d[this.typeIdentifier])
.attr('fill', colors(d[this.typeIdentifier]));
tooltip.select('#text4').text(d[this.yAxisValue]);
tooltip.select('#text5').text(d[this.xAxisValue]);
const tWidth = tooltip.select('#text1').node().getComputedTextLength() > 60 ? tooltip.select('#text1').node().getComputedTextLength() + 20 : 80;
tooltipRect.attr('width', tWidth);
const xPosition = d3.mouse(j[b])[0];
const yPosition = d3.mouse(j[b])[1];
if (xPosition + tWidth + 35 < this.xWIDTH) { // display on the right
tooltip.attr("transform", `translate(${xPosition + 15}, ${yPosition - 25})`);
} else { // display on the left
tooltip.attr("transform", `translate(${xPosition - tWidth - 15}, ${yPosition - 25})`);
}
})
.on('mouseleave', d => {
tooltip.style("display", "none");
})
因此,当您将鼠标悬停在一条线上时,这应该会将与其关联的线和点放在前面,不透明度为1,但由于某种原因,它仅适用于lines 选择,并且不在myCircles 选择中。选择不是空的,我一直在打印它们来测试它。此外,我尝试使用 .raise() 方法将圆圈一个一个(带有单一选择和原始元素)带到前面,但它不起作用。
为什么它不起作用?是否与将鼠标悬停在圆圈上的工具提示有关?我做错了什么而没有看到吗?
【问题讨论】:
标签: javascript d3.js svg