代码之家  ›  专栏  ›  技术社区  ›  Dave

在d3中,当我滚动折线图时,如何包括文本和背景框?

  •  0
  • Dave  · 技术社区  · 8 年前

      svg.append("g")
          .attr("class", "x axis")
          .attr("transform", "translate(0," + height + ")")
          .call(xAxis);
    
      svg.append("g")
          .attr("class", "y axis")
          .call(yAxis)
        .append("text")
          .attr("transform", "rotate(-90)")
          .attr("y", 6)
          .attr("dy", ".71em")
          .style("text-anchor", "end")
          .text("Value");
    
      svg.append("path")
          .datum(data)
          .attr("class", "line")
          .attr("d", line);
    
      var focus = svg.append("g")
          .attr("class", "focus")
          .style("display", "none");
    
      focus.append("circle")
          .attr("r", 4.5);
    
      var rect = focus.append("rect")
        .attr("x", 9)
        .attr("dy", ".35em")
        .attr("width", 50)
        .attr("height", 50)
        .attr("fill", "yellow");
    
        ...
    
      function mousemove() {
        var x0 = x.invert(d3.mouse(this)[0]),
            i = bisectDate(data, x0, 1),
            d0 = data[i - 1],
            d1 = data[i],
            d = x0 - d0.date > d1.date - x0 ? d1 : d0;
        focus.attr("transform", "translate(" + x(d.index_date) + "," + y(d.value) + ")");
        rect.select("text").text(formatCurrency(d.value));
      }
    

    https://jsfiddle.net/xx77tzn3/9/

    1 回复  |  直到 8 年前
        1
  •  0
  •   M. Davis    8 年前

    <svg> 的(相当不直观)不允许您附加 text 元素到 rect

    //var text = focus.append("text")
    

    并评论:

    var text = rect.append("text")
    

    然后单击鼠标功能,将第113行更改为:

    focus.select("text").text(formatCurrency(d.value));
    

    <g> .

    编辑 :为了格式化要 矩形 ,您需要使文本的坐标相对于 <g> ,而不是 .即:

    var text = focus.append("text")
      //var text = rect.append("text")
          .attr("x", 10)
          .attr("y", 10);
    

    在矩形的顶部。

    Updated js.fiddle

    推荐文章