1

我正在制作一个交互式工具,用于使用 d3.js、svg 和 JQuery创建像这样的 Sunburst 图。绘制图表的代码来自该页面,稍作修改。我正在尝试在图表的各个部分上绘制文本标签,但尽管元素显示在 Web Inspector (Chrome) 中,但它们在屏幕上不可见。我试图从这里调整代码,并且在某种程度上这已经奏效(Web Inspector 说元素存在),但我对为什么元素本身没有出现感到困惑。这是我的代码 - 用于绘制标签的部分靠近底部。我只会使用带有标签的示例页面中的代码,但布局非常不同,我必须从头开始。

var width = 850,
height = 850,
radius = Math.min(width, height) / 2;

var svg = d3.select("#vis-wrap")
    .insert("svg", "*")
    .attr("width", width)
    .attr("height", height)
    .append("g")
    .attr("transform", "translate(" + width / 2 + "," + height * 0.52 + ")");

var partition = d3.layout.partition()
    .sort(null)
    .size([2 * Math.PI, radius * radius])
    .value(function(d) { return 1; });

var arc = d3.svg.arc()
    .startAngle(function(d) { return d.x; })
    .endAngle(function(d) { return d.x + d.dx; })
    .innerRadius(function(d) { return Math.sqrt(d.y); })
    .outerRadius(function(d) { return Math.sqrt(d.y + d.dy); });

var path = svg.datum(data).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 d.color;} )
.style("fill-rule", "evenodd")
.each(stash);

// Problem here
path.insert("text", "*")
    .attr("transform", function(d) { return "rotate(" + (d.x + d.dx / 2 - Math.PI / 2) / Math.PI * 180 + ")"; })
    .attr("x", function(d) { return Math.sqrt(d.y); })
    .attr("dx", "6") // margin
    .attr("dy", ".35em") // vertical-align
    .text(function(d) { return d.name; });

d3.selectAll("input[name=mode]").on("change", function change() {
    var value = this.value === "count"
        ? function() { return 1; }
        : function(d) { return d.size; };

    path.data(partition.value(value).nodes)
        .transition()
        .duration(1500)
        .attrTween("d", arcTween);
  });


// Stash the old values for transition.
function stash(d) {
  d.x0 = d.x;
  d.dx0 = d.dx;
}

// Interpolate the arcs in data space.
function arcTween(a) {
  var i = d3.interpolate({x: a.x0, dx: a.dx0}, a);
  return function(t) {
    var b = i(t);
    a.x0 = b.x;
    a.dx0 = b.dx;
    return arc(b);
  };
}

d3.select(self.frameElement).style("height", height + "px");
4

1 回答 1

2

您正在使文本成为路径的子项,即

<path ...>
   <text>something</text>
</path>

恐怕这是无效的。您需要使文本元素成为同级元素。

令人困惑的是,<g>您已将创建的元素称为 svg 但它希望成为该元素的子元素,即

svg.insert("文本")

而不是 path.insert("text")

于 2013-04-15T18:54:59.847 回答