[Chartjs]-Creating a grouped and stacked chart in Chart.js

12👍

You can stack bar charts by setting the stacked option to true on the x- and y-axis and define stack group property of your datasets.

Below is your snippet with the proposed changes:

new Chart(document.getElementById("MyChart"), {
  type: 'bar',
  data: {
    labels: [2017, 2018, 2019, 2020, 2021, 2022, 2023],
    datasets: [{
      label: "Income - Base",
      type: "bar",
      stack: "Base",
      backgroundColor: "#eece01",
      data: [30, 31, 32, 33, 34, 35, 36],
    }, {
      label: "Tax - Base",
      type: "bar",
      stack: "Base",
      backgroundColor: "#87d84d",
      data: [-15, -16, -17, -18, -19, -20, -21],
    }, {
      label: "Income - Sensitivity",
      type: "bar",
      stack: "Sensitivity",
      backgroundColor: "#f8981f",      
      data: [20, 21, 22, 23, 24, 25, 26],
    }, {
      label: "Tax - Sensitivity",
      type: "bar",
      stack: "Sensitivity",
      backgroundColor: "#00b300",
      backgroundColorHover: "#3e95cd",
      data: [-10, -11, -12, -13, -14, -15, -16]
    }]
  },
  options: {
    scales: {
      xAxes: [{
        //stacked: true,
        stacked: true,
        ticks: {
          beginAtZero: true,
          maxRotation: 0,
          minRotation: 0
        }
      }],
      yAxes: [{
        stacked: true,
      }]
    },
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
<canvas id="MyChart" width="400" height="200"></canvas>

Leave a comment