0

Scenario: I need to show a bar chart about payment details, how much the customers paid for a product using Card, Cheque or Cash. And also need to display the total value in a stacked bar chart.

var chart = c3.generate({
    data: {
        columns: [
            ['Cash', 30, 200, 100, 400, 150, 250],
            ['Card', 130, 100, 140, 200, 150, 50],
            ['Total', 160,300,240,600,300,300]
        ],
        groups:[['Cash','Card']],
        type: 'bar'
    }
});

Output:

enter image description here

I need to show the Total value but not the bar and the legend. How can do this? Any advice would be helpful. Thank you.

Ranjith Varatharajan
  • 1,596
  • 1
  • 33
  • 76

1 Answers1

1

You don't need the total dataset, you can alter the tooltip contents to calculate it on the fly (adapting the technique found in the answer here -> https://stackoverflow.com/a/36789099/368214)

var chart = c3.generate({
    data: {
        columns: [
            ['Cash', 30, 200, 100, 400, 150, 250],
            ['Card', 130, 100, 140, 200, 150, 50],
        ],
        groups:[['Cash','Card']],
        type: 'bar'
    }, 
    tooltip : {
        contents: function (d, defaultTitleFormat, defaultValueFormat, color) {
            var total = d.reduce (function(subTotal,b) { return subTotal + b.value; }, 0);
            d.push ({value: total, id: "Total", name: "Total", x:d[0].x , index:d[0].index});
            return this.getTooltipContent(d, defaultTitleFormat, defaultValueFormat, color);
        }
    }
});

The total value is calculated using .reduce to sum all the other values at that point. Then make a new data point for the tooltip called 'Total' using that value and pass it to the default renderer for drawing (this.getTooltipContent)

http://jsfiddle.net/vz1rwvwn/

Community
  • 1
  • 1
mgraham
  • 6,147
  • 1
  • 21
  • 20