【问题标题】:Add number / text inside d3 path [duplicate]在d3路径中添加数字/文本[重复]
【发布时间】:2015-07-03 08:32:21
【问题描述】:

如何使用 d3 在圆弧内添加文本或数​​字标签?

我已经按照我想要的方式绘制了路径,但很难将文本放入其中?

我想在路径的开头为每个路径添加“count”的值

我在下面添加了我目前拥有的东西以及创建了一支笔(见下面的链接)

CODEPEN LINK

var width = 300, height = 300;
var twoPi = 2 * Math.PI; // Full circle
var formatPercent = d3.format(".0%");

var data = [
  { "count" : 1000 },
  { "count" : 800 },
  { "count" : 800 },
  { "count" : 700 }
];

var max = d3.max(data, function(d) { 
  return +d.count;
});

var percent = d3.max(data, function(d) { 
  return +d.count / 10;
});

var radius = .25;
var gap = 22;
var maxCount = max + percent;

var cx = width / 2.5;
var cy = height / 2.5;

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

    svg.selectAll("path")
        .data(data).enter()
      .append("path")
        .each(drawArc);

function drawArc(d, i) {
  var ratio = d.count / maxCount;
  var arc = d3.svg.arc()
        .startAngle(0)
        .endAngle(twoPi * ratio)
        .innerRadius(0 + gap * radius)
        .outerRadius(20 + gap * radius);

  d3.select(this)
        .attr("transform", "translate(" + cx + "," + cy + ")")
        .attr("d", arc);
        radius++;
}

【问题讨论】:

    标签: javascript d3.js path label line


    【解决方案1】:

    这已经是answered

    您需要为路径分配一个 id,然后在指向相应路径 id 的文本节点中设置 xlink:href 属性。

    var text = svg.append("text")
        .attr("x", 6)
        .attr("dy", 15);
    
    text.append("textPath")
        .attr("xlink:href","#yourPathId")
        .text("My counter text");
    

    This is the codepen 进行了一些更改以反映这一点。

    【讨论】:

    • 谢谢,这很完美。我不会对答案投票,因为我的代表低于 15。当我超过 15 时,我会投票。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-18
    • 2013-12-29
    • 1970-01-01
    相关资源
    最近更新 更多