[Chartjs]-ChartJS 2.7.3 stacked bar chart with overlap

1👍

Ok so I solved this myself. You need to set yAxisID to each dataset, and then define which will be stacked and which one isn’t.

Here’s the code:

var data = {
  labels: ["x1", "x2", "x3"],
  datasets: [{
    label: "First",
    backgroundColor: 'rgba(255, 99, 132, 0.2)',
    borderWidth: 1,
    data: [10, 20, 30],
    xAxisID: "bar-x-axis1",
    yAxisID: "bar-y-axis1"
  },
  {
    label: "Second",
    backgroundColor: 'green',
    borderWidth: 1,
    data: [5, 7, 9],
    xAxisID: "bar-x-axis1",
    yAxisID: "bar-y-axis1"
  },
  {
    label: "Third",
    backgroundColor: 'rgba(255, 206, 86, 0.2)',
    borderWidth: 1,
    data: [5, 30, 35],
    xAxisID: "bar-x-axis2",
    yAxisID: "bar-y-axis2"
  }]
};

var options = {
  scales: {
    xAxes: [{
      stacked: true,
      id: "bar-x-axis1",
      barThickness: 30,
    }, {
      display: false,
      stacked: true,
      id: "bar-x-axis2",
      barThickness: 70,
      // these are needed because the bar controller defaults set only the first x axis properties
      type: 'category',
      categoryPercentage: 0.8,
      barPercentage: 0.9,
      gridLines: {
        offsetGridLines: true
      },
      offset: true
    }],
    yAxes: [
    {
        id: "bar-y-axis1",
      stacked: true,
      ticks: {
        beginAtZero: true,
        min: 0,
        max: 40,
                autoSkip: false, 
      }
    },
      {
        id: "bar-y-axis2",
        stacked: false,
        ticks: {
          beginAtZero: true,
          min: 0,
          max: 40,
                    autoSkip: false,
          display: false
        },
        gridLines: {
            display: false
        }
    }]

  }
};

var ctx = document.getElementById("myChart").getContext("2d");
var myBarChart = new Chart(ctx, {
  type: 'bar',
  data: data,
  options: options
});

And a Fiddle: https://jsfiddle.net/f1ret02b/2/

Leave a comment