繁体   English   中英

向d3森伯斯特添加标签

[英]Adding labels to d3 sunburst

我试图在此处修改D3朝阳示例( http://bl.ocks.org/mbostock/4063423 )以向圆弧添加标签。

我添加了代码来计算角度并生成文本(从本示例中获取: http : //jsfiddle.net/4PS53/6/ ),但是它不起作用。 文本只是不显示,当我尝试使用检查器检查<text>元素时,它们似乎不在DOM中。

任何帮助深表感谢! 下方是JS代码(从原始D3库示例进行了修改),JSON数据相同。 我正在展示我修改的代码部分; 其余的都一样。

d3.json("data.json", function(error, root) {
  console.log(root);
  var path = svg.datum(root).selectAll("path")
      .data(partition.nodes)
      .enter().append("path")
      .attr("display", function(d) { return d.depth ? null : "none"; }) // hide inner ring
      .attr("d", arc)
      .style("stroke", "#fff")
      .style("fill", function(d) { return color((d.children ? d : d.parent).name); })
      .style("fill-rule", "evenodd")
      .each(stash);

  path.append("text")
        .text(function(d) { return d.name})
        .classed("label", true)
        .attr("x", function(d) { return d.x; })
        .attr("text-anchor", "middle")
        // translate to the desired point and set the rotation
        .attr("transform", function(d) {
            if (d.depth > 0) {
                return "translate(" + arc.centroid(d) + ")" +
                       "rotate(" + getAngle(d) + ")";
            }  else {
                return null;
            }
        })
        .attr("dx", "6") // margin
        .attr("dy", ".35em") // vertical-align
        .attr("pointer-events", "none");

});

function getAngle(d) {
    // Offset the angle by 90 deg since the '0' degree axis for arc is Y axis, while
    // for text it is the X axis.
    var thetaDeg = (180 / Math.PI * (arc.startAngle()(d) + arc.endAngle()(d)) / 2 - 90);
    // If we are rotating the text by more than 90 deg, then "flip" it.
    // This is why "text-anchor", "middle" is important, otherwise, this "flip" would
    // a little harder.
    return (thetaDeg > 90) ? thetaDeg - 180 : thetaDeg;
}

您需要g组元素来添加文本,因此您可以更改:

var path = svg.datum(root).selectAll("path")
  .data(partition.nodes)
  .enter().append("path")
  .attr("display", function(d) { return d.depth ? null : "none"; }) // hide inner ring
  .attr("d", arc)
  .style("stroke", "#fff")
  .style("fill", function(d) { return color((d.children ? d : d.parent).name); })
  .style("fill-rule", "evenodd")
  .each(stash);

var path = svg.datum(root).selectAll("path")
  .data(partition.nodes)
  .enter().append("g")

path.append("path")
  .attr("display", function(d) { return d.depth ? null : "none"; }) // hide inner ring
  .attr("d", arc)
  .style("stroke", "#fff")
  .style("fill", function(d) { return color((d.children ? d : d.parent).name); })
  .style("fill-rule", "evenodd")
  .each(stash);

检查此jsFiddle: http : //jsfiddle.net/5d0zd2s7/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM