在Barchart D3js上添加标签文本

3
我正在尝试找出在我的柱状图中放置在每个柱子上方的标签的正确方法。我还希望它们在数字后面显示一个百分号。
这是我的 Plunker:https://plnkr.co/edit/FbIquWxfLjcRTg7tiX4E?p=preview 我尝试使用下面链接中的问题中的代码进行实验。但是,我无法使其正常工作(即整个图表都无法显示)。 在 D3 柱状图上添加标签
var yTextPadding = 20;
svg.selectAll(".bartext")
.data(data)
.enter()
.append("text")
.attr("class", "bartext")
.attr("text-anchor", "top")
.attr("fill", "white")
.attr("x", function(d,i) {
    return x(i)+x.rangeBand()/2;
})
.attr("y", function(d,i) {
    return height-y(d)+yTextPadding;
})
.text(function(d){
     return d;
});
1个回答

6

根据你现有的代码,这是最直接的方法:

    // keep a reference to the g holding the rects
    var rectG = g.append("g")
        .selectAll("g")
        .data(data)
        .enter().append("g")
        .attr("transform", function(d) { return "translate(" + x0(d.State) + ",0)"; })
        .selectAll("rect")
        .data(function(d) { return keys.map(function(key) { return {key: key, value: d[key]}; }); })
        .enter();

    // append the rects the same way as before
    rectG.append("rect")
        .attr("x", function(d) { return x1(d.key); })
        .attr("y", function(d) { return y(d.value); })
        .attr("width", x1.bandwidth())
        .attr("height", function(d) { return height - y(d.value); })
        .attr("fill", function(d) { return z(d.key); });

    // now add the text to the g
    rectG.append("text")
      .text(function(d){
        return d.value + '%';
      })
      .attr("x", function(d) { return x1(d.key) + (x1.bandwidth()/2); })
        .attr("y", function(d) { return y(d.value); })
        .style("text-anchor", "middle");

更新了plunker


太好了!这将对我其他同样风格的图表应用非常有帮助。知道我之前做法是错误的真是太好了! - Howard Smith

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接