D3 Appending Text to a SVG Rectangle

前端 未结 2 642
自闭症患者
自闭症患者 2020-11-29 00:51

I\'m looking to append html onto a rectangle in D3 to give me a multiple line tooltip. The bottom part is how I\'m adding a rectangle which may be part of the problem. The

相关标签:
2条回答
  • 2020-11-29 00:57

    A rect can't contain a text element. Instead transform a g element with the location of text and rectangle, then append both the rectangle and the text to it:

    var bar = chart.selectAll("g")
        .data(data)
      .enter().append("g")
        .attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });
    
    bar.append("rect")
        .attr("width", x)
        .attr("height", barHeight - 1);
    
    bar.append("text")
        .attr("x", function(d) { return x(d) - 3; })
        .attr("y", barHeight / 2)
        .attr("dy", ".35em")
        .text(function(d) { return d; });
    

    http://bl.ocks.org/mbostock/7341714

    Multi-line labels are also a little tricky, you might want to check out this wrap function.

    0 讨论(0)
  • 2020-11-29 01:22

    Have you tried the SVG text element?

    .append("text").text(function(d, i) { return d[whichevernode];})
    

    rect element doesn't permit text element inside of it. It only allows descriptive elements (<desc>, <metadata>, <title>) and animation elements (<animate>, <animatecolor>, <animatemotion>, <animatetransform>, <mpath>, <set>)

    Append the text element as a sibling and work on positioning.

    UPDATE

    Using g grouping, how about something like this? fiddle

    You can certainly move the logic to a CSS class you can append to, remove from the group (this.parentNode)

    0 讨论(0)
提交回复
热议问题