【问题标题】:How can I add labels to my diagram with d3.js?如何使用 d3.js 向我的图表添加标签?
【发布时间】:2013-04-15 18:49:05
【问题描述】:

我正在制作一个交互式工具,用于使用 d3.js、svg 和 JQuery 创建像 this one 这样的 Sunburst 图。绘制图表的代码来自该页面,稍作修改。我正在尝试在图表的各个部分上绘制文本标签,但尽管元素显示在 Web Inspector (Chrome) 中,但它们在屏幕上不可见。我试图从here 改编代码,并且在某种程度上这已经奏效(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");

【问题讨论】:

    标签: javascript svg d3.js label sunburst-diagram


    【解决方案1】:

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

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

    恐怕那是无效的。您需要将文本元素设为兄弟元素。

    令人困惑的是,您调用了您创建的 svg 的 &lt;g&gt; 元素,但它希望成为该元素的子元素,即

    svg.insert("文本")

    而不是 path.insert("text")

    【讨论】:

    • 谢谢,这就像做梦一样!我可能应该重命名我的 'svg' 变量... :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-31
    相关资源
    最近更新 更多