Satheesh Kumar
Satheesh Kumar

Reputation: 1

How to display total count on top of the stacked bar chart

enter image description here

Hi All i tired to display total in to top of the d3 c3 chart like attached image

Upvotes: 0

Views: 3176

Answers (1)

Dmitry Demidovsky
Dmitry Demidovsky

Reputation: 8197

You will need:

Showing only top label is simple: just check current visible labels and find the last:

function showLastLabel()
{
    var shown = chart.data.shown().map(function(item){ return item.id }) // get visible ids: ['data1', 'data2', ...]
    var last = (shown[shown.length - 1])
    d3.select('.c3-chart-texts').selectAll('.c3-target').style('display', 'none') // hide all
    d3.select('.c3-chart-texts').selectAll('.c3-target-' + last).style('display', 'block') // show last
}

Important thing is to disable stack reordering (c3 does this by default) because it breaks logic described above.

order: null,

Then, calculating total top label needs additional check for visibility:

labels: {
    format: function(v, id, i, j)
    {
        if (isNaN(totals[i])) totals[i] = 0

        // sum only visible
        if (chart)
        {
            var shown = chart.data.shown().map(function(item){ return item.id })
            if (shown.indexOf(id) != -1) totals[i] += v
        }
        else
        {
            totals[i] += v
        }

        return totals[i]
    }
},

At last we update labels' visibility when clicking on legend items:

legend: {
  item: {
    onclick: function (id) { 
        chart.toggle([id]) // keep default functionality
        showLastLabel()
    }
  }
},

See full example here

Upvotes: 3

Related Questions