【问题标题】:Add path but also text above the path - D3js v3?添加路径以及路径上方的文本 - D3js v3?
【发布时间】:2017-05-01 03:02:54
【问题描述】:

尝试在此 Zoomable Sunburst 图中的路径上方添加文本数据:Zoomable Sunburst 我有这个代码:

d3.json(jsonUrl, function(error, data) {
    if (error) {
        throw error;
    }

    svg.selectAll("g")
        .data(partition.nodes(data))
        .enter()
        .append("g")
        .append("path")
        .attr("d", arc)
        .style("fill", function(d) { 
            return color((d.children ? d : d.parent).name); 
        })
        .on("click", self.click)
        .append("text")
        .text(function(d) {
            //console.dir(d);
            return d.name + "\n" + formatNumber(d.value); 
        });
    });

但它不起作用。没有文字显示。我知道它是这样的,但我做错了什么。我目前使用的是 D3js 版本 3。

一些想法?

【问题讨论】:

  • 尝试添加一个 textPath 作为“text”元素的子元素。将 .text 放在 textPath 元素上。
  • 除了罗伯特·朗森伪装成评论的回答外,您还必须知道哪些元素可以是父母,哪些元素可以是孩子。您不能将文本附加到路径。在这里查看:stackoverflow.com/documentation/d3.js/2537/…
  • 试过 .append("text").append("textPath").text(/*get text for the path*/) 并且它把带有子标签 标签放在里面 标签当然不起作用。虽然在 html 部分的 Firebug 中可见,但我没有看到文本。

标签: javascript d3.js svg data-visualization


【解决方案1】:

我刚刚找到了这个Donut Chart 示例并更改了我的代码中的一些部分。 尽管它看起来很杂乱,但它确实可以完成工作。也许通过一些抛光,我可以获得不错的外观:

这是我的代码:

var svg = d3.select("body")
        .append("svg")
        .attr("width", width)
        .attr("height", height)
        .append("g")
        .attr("transform", "translate(" + (width / 2) + "," + (height / 2) + ")"),
g = null;

d3.json(dataFile, function(error, data) {
    if (error) {
        throw error;
    }

    g = svg.selectAll(".arc")
        .data(partition.nodes(data))
        .enter()
        .append("g")
        .attr("class", "arc");

    g.append("path")
        .attr("d", arc)
        .style("fill", function(d) { 
            return color((d.children ? d : d.parent).name); 
        })
        .on("click", self.click);

    g.append("text")
        .attr("transform", function (d) { 
            return "translate(" + arc.centroid(d) + ")"; 
        })
        .attr("dy", ".35em")
        .text(function (d) { 
            return d.name + "\n" + formatNumber(d.value);
        });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-18
    • 1970-01-01
    • 1970-01-01
    • 2013-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多