B. Clay Shannon B. Clay Shannon - 2 months ago 19
CSS Question

How is it possible to create a stacked bar / horizontal chart with Chart.JS?

I can create a "traditional" bar chart using Chart.JS, and even a stacked bar chart that looks like this:

enter image description here

But I need to create one that sports horizontal, rather than vertical, bars and which displays percentages along the bottom, a la this example shown below created using xlsxwriter:

enter image description here

How can Chart.JS be manipulated to perform wizardry of this order?

Answer
  1. If you want to create a horizontal bar instead of a regular char you can use type: 'horizontalBar'.
  2. To create the chart as "stacked bar" you need to set


xAxes: [{
    stacked: true
}],
yAxes: [{
    stacked: true
}]

You can use this code:

var config = {
  type: 'horizontalBar',
  data: {
    labels: ["A", "B", "C", "D", "E"],
    datasets: [{
      label: "Dataset 1",
      backgroundColor: "rgba(154,178,96,0.5)",
      hoverBackgroundColor: "rgba(154,178,96,1)",
      data: [10, 15, 5, 81, 55],
    }, {
      label: "Dataset 2",
      backgroundColor: "rgba(197,213,167,0.5)",
      hoverBackgroundColor: "rgba(197,213,167,1)",
      data: [90, 85, 95, 19, 45]
    }]
  },
  options: {
    scales: {
      xAxes: [{
        stacked: true
      }],
      yAxes: [{
        stacked: true
      }]
    }
  }
};

var ctx = document.getElementById("myChart").getContext("2d");
new Chart(ctx, config);

Here is a working example:
https://jsfiddle.net/0xLxum4s/

(For some reason it didn't work in so snippet so I used jsfiddle).