Home > Blockchain >  Can't view multiple bars on the x axis - vue-chart
Can't view multiple bars on the x axis - vue-chart

Time:07-01

I'm trying to get a stacked bar chart with two bars sharing a label next to each other on the x-axis but I'm having issues with getting the 2nd bar to display - currently it sits underneath the first bar (if you hide the 2021 value, you will see the 2022 bar will appear):

var barChartData = {
  labels: ["January", "February"],
  datasets: [{
    data: [10, 20],
    label: '2021',
    backgroundColor: "#ffe100",
    yAxisId: 'y-stacked',
  }, {
    data: [15, 30],
    label: '2021 Total',
    backgroundColor: "#ee0000",
    yAxisId: 'y-stacked',
  }, {
    data: [6, 19],
    label: '2022 YTD',
    backgroundColor: "#555555",
  }]
};

var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx, {
  type: 'bar',
  data: barChartData,
  options: {
    title: {
      display: true,
      text: "Chart.js Bar Chart - Stacked"
    },
    tooltips: {
      mode: 'label'
    },
    responsive: true,
    scales: {
      xAxes: [{
        stacked: true,
      }],
      yAxes: [{
        stacked: false,
        ticks: {
          beginAtZero: true,
        }
      }, {
        id: "y-stacked",
        stacked: true,
        display: false,
        ticks: {
          beginAtZero: true,
          min: 0,
        },
        type: 'linear'
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.js"></script>

<div style="width: 100%">
  <canvas id="canvas"></canvas>
</div>

Is there any way I can get the 2022 bar to show next to the 2021 bar?

I have tried adding another x-axis and changing the value of the x-axis stack to false but this just unstacks all three bars and sits them all next to each other

CodePudding user response:

Turns out there is a stacked property you can use on the datasets and you don't need multiple axes

var barChartData = {
  labels: ["January", "February"],
  datasets: [{
    data: [10, 20],
    label: '2021',
    backgroundColor: "#ffe100",
    stack: 'stack 1',
  }, {
    data: [15, 30],
    label: '2021 Total',
    backgroundColor: "#ee0000",
    stack: 'stack 1',
  }, {
    data: [6, 19],
    label: '2022 YTD',
    backgroundColor: "#555555",
    stack: 'stack 2',
  }]
};

var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx, {
  type: 'bar',
  data: barChartData,
  options: {
    title: {
      display: true,
      text: "Chart.js Bar Chart - Stacked"
    },
    tooltips: {
      mode: 'label'
    },
    responsive: true,
    scales: {
      xAxes: [{
        stacked: true,
      }],
      yAxes: [{
        stacked: true,
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.js"></script>

<div style="width: 100%">
  <canvas id="canvas"></canvas>
</div>

  • Related