Howard Smith
Howard Smith

Reputation: 328

Adding Label Text on Barchart D3js

I'm trying to figure out the correct way to displays labels that will sit on top of each bar in my bar chart. I'd also like them to display a % after the number.

Here is my Plunker: https://plnkr.co/edit/FbIquWxfLjcRTg7tiX4E?p=preview

I experimented with using this code from the question found in the link below. However, I wasnt able to get it to work properly (meaning the whole chart failed to display)

Adding label on a D3 bar chart

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;
});

Upvotes: 3

Views: 2673

Answers (1)

Mark
Mark

Reputation: 108512

This is the most straight forward way given your existing code:

    // 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");

Updated plunker.

Upvotes: 6

Related Questions