Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display inline values in a stacked bar chart with Chart.js?

I am using the Chart.js library to display some values in stacked bars but I am struggling in trying to find out how to display the values inside of the bars, that is,

enter image description here

Right now, I have the following code that displays the numbers on top of the bars but I would like to know how can I display them inside of the bars.

var numberWithCommas = function(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  };

var dataPack1 = [50000, 22000, 26000, 35000, 55000, 55000, 56000, 59000, 60000, 61000, 60100, 62000];

var dataPack2 = [0, 6000, 13000, 14000, 50060, 20030, 20070, 35000, 41000, 4020, 40030, 70050];

var dates = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

// Chart.defaults.global.elements.rectangle.backgroundColor = '#FF0000';

var bar_ctx = document.getElementById('bar-chart');
var bar_chart = new Chart(bar_ctx, {
    type: 'bar',
    data: {
        labels: dates,
        datasets: [
        {
            label: 'SoftEnterprises, Sales',
            data: dataPack1,
						backgroundColor: "rgba(55, 160, 225, 0.7)",
						hoverBackgroundColor: "rgba(55, 160, 225, 0.7)",
						hoverBorderWidth: 2,
						hoverBorderColor: 'lightgrey'
        },
        {
            label: 'SmartSystems, Sales',
            data: dataPack2,
						backgroundColor: "rgba(225, 58, 55, 0.7)",
						hoverBackgroundColor: "rgba(225, 58, 55, 0.7)",
						hoverBorderWidth: 2,
						hoverBorderColor: 'lightgrey'
        },
        ]
    },
    options: {
     		animation: {
        	duration: 10,
          onComplete: function(){
                var chartInstance = this.chart,
                ctx = chartInstance.ctx;
                ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);
                ctx.textAlign = 'center';
                ctx.textBaseline = 'bottom';
                ctx.fillStyle = '#000';
                                this.data.datasets.forEach(function(dataset, i) {
                var isHidden = dataset._meta[0].hidden; //'hidden' property of dataset
                if (!isHidden) { //if dataset is not hidden
                    var meta = chartInstance.controller.getDatasetMeta(i);
                    meta.data.forEach(function(bar, index) {
                    var data = dataset.data[index];
                    ctx.fillText(data, bar._model.x, bar._model.y - 5);
                });
               }
            });
          
          }
        },
        tooltips: {
					mode: 'label',
          callbacks: {
          label: function(tooltipItem, data) { 
          	return data.datasets[tooltipItem.datasetIndex].label + ": " + numberWithCommas(tooltipItem.yLabel);
          }
          }
         },
        scales: {
          xAxes: [{ 
          	stacked: true, 
            gridLines: { display: false },
            }],
          yAxes: [{ 
          	stacked: true, 
            ticks: {
        			callback: function(value) { return numberWithCommas(value); 
              },
     				}, 
            }],
        }, // scales
        legend: {display: true}
    } // options
   },
   
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>

<canvas id="bar-chart" width="600" height="350"></canvas>
like image 675
abautista Avatar asked Nov 03 '17 23:11

abautista


People also ask

Can you do a stacked bar chart with line?

Like a Grouped Bar with Line chart, a Stacked Bar with Line chart includes two y-axes, one on each side of the chart. One of these is used to measure the values along the line(s), and the other is used to measure the values of the bars.

How do you graph a vertical line in Javascript?

Anytime you want to draw a vertical line, add a data object like { x: where_the_line_goes, y: 1 } to your bar chart dataset. The pen also adds some custom data to the bar chart dataset and a legend filter and label callback to exclude the bar chart dataset from the legend, and control the label on the vertical line.

What is a segmented bar chart?

A segmented Bar chart is one kind of stacked bar chart, but each bar will show 100% of the discrete value. For example, there are a total of 40 students in your classroom. Out of them, 25 students like Basketball, 30 students like Volleyball, and 20 students like Badminton. There are 25 boys and 15 girls in the class.


1 Answers

This can be easily achieved using a Chart.js plugin called : chartjs-plugin-datalabels.

Here is the minimum options that need to be set for this plugin to display values inside (middle) of the stacked bars :

options: { //your chart options
   plugins: {
      datalabels: {
         display: true,
         align: 'center',
         anchor: 'center'
      }
   }
}

although, there are tons of other options that you can use to further customize these values/labels (inside bars), which can be found here.

ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩

var numberWithCommas = function(x) {
   return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};

var dataPack1 = [50000, 22000, 26000, 35000, 55000, 55000, 56000, 59000, 60000, 61000, 60100, 62000];

var dataPack2 = [0, 6000, 13000, 14000, 50060, 20030, 20070, 35000, 41000, 4020, 40030, 70050];

var dates = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

// Chart.defaults.global.elements.rectangle.backgroundColor = '#FF0000';

var bar_ctx = document.getElementById('bar-chart');
var bar_chart = new Chart(bar_ctx, {
   type: 'bar',
   data: {
      labels: dates,
      datasets: [{
         label: 'SoftEnterprises, Sales',
         data: dataPack1,
         backgroundColor: "rgba(55, 160, 225, 0.7)",
         hoverBackgroundColor: "rgba(55, 160, 225, 0.7)",
         hoverBorderWidth: 2,
         hoverBorderColor: 'lightgrey'
      }, {
         label: 'SmartSystems, Sales',
         data: dataPack2,
         backgroundColor: "rgba(225, 58, 55, 0.7)",
         hoverBackgroundColor: "rgba(225, 58, 55, 0.7)",
         hoverBorderWidth: 2,
         hoverBorderColor: 'lightgrey'
      }, ]
   },
   options: {
      tooltips: {
         mode: 'label',
         callbacks: {
            label: function(tooltipItem, data) {
               return data.datasets[tooltipItem.datasetIndex].label + ": " + numberWithCommas(tooltipItem.yLabel);
            }
         }
      },
      scales: {
         xAxes: [{
            stacked: true,
            gridLines: {
               display: false
            },
         }],
         yAxes: [{
            stacked: true,
            ticks: {
               callback: function(value) {
                  return numberWithCommas(value);
               },
            },
         }],
      }, // scales
      legend: {
         display: true
      },
      plugins: {
         datalabels: {
            display: true,
            align: 'center',
            anchor: 'center'
         }
      }
   } // options
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>


<canvas id="bar-chart" width="600" height="350"></canvas>
like image 60
ɢʀᴜɴᴛ Avatar answered Oct 06 '22 14:10

ɢʀᴜɴᴛ