Stacked bar charts in chart.js with different values in stacks

I want to create a stack graph something like this:

Note: Each stack has different value

enter image description here

Is it possible with chart js ? If yes what my data should look like ?

I have tried this:

var data = {
    labels: ["2018", "2019"], //Want "value 1,2,3 for 2018 and value 4,5,6 for 2019"
    datasets: [
        {
            label: "Harpo",
            fillColor: "blue",
            data: []  // What should i use here 
        },
        {
            label: "Chico",
            fillColor: "red",
            data: []  // What should i use here
        }
    ]
};

But this is not what i want.

Any help would be appreciated.

Answers:

Answer

in order to have a stack of 3 bars,
you will need 3 datasets.

to have different colors, use an array for backgroundColor.

see following working snippet...

$(document).ready(function() {
  new Chart(document.getElementById("myChart").getContext("2d"), {
    type: "bar",
    data: {
      labels: ["2018", "2019"],
      datasets: [
        {
            backgroundColor: ["#673AB7", "#90A4AE"],
            fillColor: "#000000",
            data: [1, 4]
        },
        {
            backgroundColor: ["#E1BEE7", "#0D47A1"],
            data: [2, 5]
        },
        {
            backgroundColor: ["#BA68C8", "#455A64"],
            data: [3, 6]
        }
      ]
    },
    options: {
      legend: {
        display: false
      },
      scales: {
        xAxes:[{
          stacked: true
        }],
        yAxes:[{
          stacked: true
        }],
      }
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js"></script>
<canvas id="myChart"></canvas>

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.