Create a stacked bar chart - Javascript Chart.js

Javascript examples for Chart.js:Bar Chart

Description

Create a stacked bar chart

Demo Code

ResultView the demo in separate window

<html lang="en">
   <head> 
      <title>ChartJS Stacked Charts </title> 
      <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js"></script> 
      <style>

canvas {/* www  .j a  v  a  2 s.  c  o m*/
   -moz-user-select: none;
   -webkit-user-select: none;
   -ms-user-select: none;
}


      </style> 
   </head> 
   <body translate="no"> 
      <div style="width: 75%"> 
         <canvas id="canvas"></canvas> 
      </div> 
      <script>
      // Empty scaffold that will eventually hold all of the transformed data
let barChartData = {
  labels: [],
  datasets: [],
}
let data = [
  {
  "year": "1991",
  "color":"purple",
  "value":12,
  },
  {
  "year":"1991",
  "color":"red",
  "value":8,
  },
  {
  "year": "1992",
  "color":"red",
  "value":20,
  },
  {
  "year": "1993",
  "color":"blue",
  "value":9,
  },
  {
  "year": "1993",
  "color":"red",
  "value":7,
  },
  {
  "year": "1993",
  "color":"purple",
  "value":3,
  },
]
data.forEach((val) => {
  // Add the label if it doesn't exist already
  if(!barChartData.labels.includes(val.year)) {
    barChartData.labels.push(val.year);
  }
  // Search for the correct dataset
  let valsDataset;
  let datasetName = `Dataset ${val.color}`;
  barChartData.datasets.forEach((dataset) => {
    if(dataset.label === datasetName) valsDataset = dataset;
  });
  if(valsDataset === undefined) {
    valsDataset = {
      label: datasetName,
      backgroundColor: val.color,
      data: []
    }
    barChartData.datasets.push(valsDataset);
  }
  let valIndex = barChartData.labels.indexOf(val.year);
  valsDataset.data[valIndex] = val.value;
});
      window.onload = function() {
         var ctx = document.getElementById('canvas').getContext('2d');
         window.myBar = new Chart(ctx, {
            type: 'bar',
            data: barChartData,
            options: {
               title: {
                  display: true,
                  text: 'Chart.js Bar Chart - Stacked'
               },
               tooltips: {
                  mode: 'index',
                  intersect: false
               },
               responsive: true,
               scales: {
                  xAxes: [{
                     stacked: true,
                  }],
                  yAxes: [{
                     stacked: true
                  }]
               }
            }
         });
      };
      </script>  
   </body>
</html>

Related Tutorials