Minh
Minh

Reputation: 2320

dc.js: Adding Totals to Bar Chart

I'm trying to create a bar chart in dc.js with the totals label at the end of the charts. Right now, I can't find any documentation on parameters or functions to pass through that'll allow it to happen.

Any help would be greatly appreciated!

Upvotes: 0

Views: 524

Answers (1)

Minh
Minh

Reputation: 2320

Gordon, you are correct that this is a duplicate of a problem that you mentioned in a comment!

However, I found the answer didn't work because .renderlet chaining was removed. Here's a reworked version of it that worked for me (kinda, there is still issue of it's not showing up if the bars are too small).

Thanks for everything!

  testChart
  .width(400)
  .height(200)
  .dimension(testDim)
  .group(testGroup)
  .x(d3.scale.ordinal())
  .xUnits(dc.units.ordinal)

  testChart.on('renderlet', function (chart) {

    var barsData = [];
    var bars = chart.selectAll('.bar').each(function (d) {
      barsData.push(d);
    });

    //Remove old values (if found)
    d3.select(bars[0][0].parentNode).select('#inline-labels').remove();
    //Create group for labels
    var gLabels = d3.select(bars[0][0].parentNode).append('g').attr('id', 'inline-labels');

    for (var i = bars[0].length - 1; i >= 0; i--) {

      var b = bars[0][i];
      //Only create label if bar height is tall enough
       if (+b.getAttribute('height') < 10) continue;

      gLabels.append("text")
          .text(barsData[i].data.value)
          .attr('x', +b.getAttribute('x') + (b.getAttribute('width') / 2))
          .attr('y', +b.getAttribute('y') + 25)
          .attr('text-anchor', 'middle')
          .attr('fill', 'black');
    }
  });

Upvotes: 1

Related Questions