看看小提琴,你用来渲染矩形的比例似乎不是
yScale
,但实际上只是
y
更改以下片段:
const y = yScale(actual.y + actual.y0)
line = svg.append('line')
.attr('id', 'limit')
.attr('x1', 0)
.attr('y1', y)
.attr('x2', width)
.attr('y2', y);
致:
const limitY = y(actual.y + actual.y0);
line = svg.append('line')
.attr('id', 'limit')
.attr('x1', 0)
.attr('y1', limitY)
.attr('x2', width)
.attr('y2', limitY);
调整线条的位置以匹配矩形,因为它现在使用的比例与条形图和轴使用的比例相同。
关于工具提示,我看到你想附加一个矩形:
line.append("rect")
.attr("width", "10px")
.attr("height", "10px")
.style("fill", "red");
然而,a
<line>
不能有
<rect>
内部元素。你真正想要的是添加
<rect>
到
<svg>
:
svg.append("rect")
.attr('id', 'myId') // Also give it an Id for clean up
.attr("width", "10px")
.attr("height", "10px")
.attr("y", limitY) // The limitY is available to position the tooltip under the line
.style("fill", "red");
不要忘记在mouseout事件中删除它,就像你正在做的那样
<line#limit>
:
.on("mouseout", function() {
svg.selectAll('#limit').remove();
// clean the rectangle on mouseout:
svg.selectAll('#myId').remove();
})
你可以使用与上述相同的前提
<rect>
在一个
<g>
元素来创建包含文本和背景的完整工具提示,但对其进行编码超出了此答案的范围。我希望以上的解释能给你一个方向。
这是
a fiddle with the changes
.