我如何添加标签到我的图表d3.js



我正在制作一个交互式工具,用于创建像d3.js, svg和JQuery这样的Sunburst图表。用于绘制图表的代码来自该页面,并进行了一些小的修改。我试图在图表的部分上绘制文本标签,但是虽然元素显示在Web检查器(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");

让文本成为路径的子元素,即

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

恐怕这是无效的。您需要将text元素设置为兄弟元素。

让人困惑的是,你把<g>元素叫做你创建了svg但它想成为它的子元素,也就是

svg.insert("文本")

而不是path.insert("text")

最新更新