【问题标题】:D3 pie (donut) chart label outside of each arc每个圆弧外的 D3 饼图(甜甜圈)图表标签
【发布时间】:2014-01-09 11:21:37
【问题描述】:

我是 D3 的新手,我有我的圆环图,但是我无法在每个弧之外获得弧标签。

我想在 http://bl.ocks.org/Guerino1/2295263 中获得类似紫色标签的东西,但我无法让它适用于我的圆环图。

我正在使用以下代码附加每个弧的标签,但似乎 arc.centroid 没有按预期工作。

        var arcs = vis.selectAll("g.slice")
    arcs.append("svg:text")
      .attr("transform", function(d, i) { //set the label's origin to the center of the arc
        d.outerRadius = svgOuterRadius + 40; // Set Outer Coordinate
        d.innerRadius = svgOuterRadius + 35; // Set Inner Coordinate
        return "translate(" + arc.centroid(d) + ")";
      })
      .attr("text-anchor", "middle") //center the text on it's origin
      .style("fill", "Purple")
      .style("font", "bold 14px Arial")
      .text(function(d, i) { return 'label'+i; }); //get the label from our original

Here 是我的 JSfiddle:

我真的很感激。

【问题讨论】:

    标签: d3.js label donut-chart


    【解决方案1】:

    基本问题是您的弧path 段已翻译,而您在添加标签时没有考虑该翻译。如果您查看已链接到的示例,您会看到 path 段是在没有任何翻译的情况下添加的,这意味着可以添加 text 元素而无需额外的偏移量。

    要修复,只需考虑偏移量:

    arcs.append("svg:text")
          .attr("transform", function(d, i) { //set the label's origin to the center of the arc
              var c = arc.centroid(d);
            return "translate(" + (svgWidth/2 + c[0]) + "," + (svgHeight/2 + c[1]) + ")";
    })
    // etc
    

    完整示例here

    【讨论】:

    • 非常感谢,它看起来很棒。我能再问你一件事吗?我希望每个标签都在每个弧之外,但是添加 d.outerRadius = + 50; d.innerRadius = + 45;在 arc.centroid(d) 没有帮助之前。你知道我怎样才能得到每个弧之外的每个标签位置吗?
    • This question 应该会有所帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多