admin管理员组

文章数量:1415420

I want to create a stack graph something like this:

Note: Each stack has different value

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.

I want to create a stack graph something like this:

Note: Each stack has different value

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.

Share Improve this question asked Nov 20, 2018 at 2:22 user2985842user2985842 4579 silver badges25 bronze badges 1
  • 4 how on earth did you draw this example graph – schellmax Commented Nov 20, 2018 at 13:20
Add a ment  | 

1 Answer 1

Reset to default 5

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./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js"></script>
<canvas id="myChart"></canvas>

本文标签: javascriptStacked bar charts in chartjs with different values in stacksStack Overflow