代码之家  ›  专栏  ›  技术社区  ›  Noor A Shuvo

为什么堆栈条形图中的水平线不能正常工作

  •  0
  • Noor A Shuvo  · 技术社区  · 4 年前

    我有一个堆叠条形图。你可以看到小提琴 here .

    我画了一条线,它实际上是一条水平线,将当前的条形图水平对齐。下面是代码。

    .on('用户界面',函数(实际值,i){

              const y = yScale(actual.y + actual.y0);
                                debugger;
              line = svg.append('line')
                .attr('id', 'limit')
                .attr('x1', 0)
                .attr('y1', y)
                .attr('x2', width)
                .attr('y2', y);
    

    输出为, enter image description here

    在这里,你可以看到,对于月度数据,这条线是正确的。但对于季度数据,这条线略高于实际位置。对于年度数据,这条线没有显示。

    这里有什么问题? 我如何在线条旁边显示工具提示? enter image description here

    0 回复  |  直到 4 年前
        1
  •  1
  •   Rodrigo Divino    4 年前

    看看小提琴,你用来渲染矩形的比例似乎不是 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 .