繁体   English   中英

如何使用d3.js在图表中添加标签?

[英]How can I add labels to my diagram with d3.js?

我正在制作一个交互式工具,用于使用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");

您正在将文本作为路径的子元素,即

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

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

令人困惑的是,您已经创建了svg调用了<g>元素,但它想成为该元素的子元素,即

svg.insert( “文本”)

而不是path.insert(“ text”)

暂无
暂无

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

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