javascriptchart.js

How to remove space between bars in a mixed Bar chart?


I need to draw a bar chart, not exactly but somewhat similar, like in the first picture. I have one stacked bar consisting of 2 bars one narrow bar and one non-stacked with the same width as the stacked bar.

I don´t want to have any space between them. When I play around with barPercentage and categoryPercentage I only get spaces around the narrow bar.

This is what I want:

enter image description here

And this is the only thing I can reproduce:

enter image description here

With this code:

const ctx = document.getElementById('capacityOverviewChart').getContext('2d');
const data = {
  datasets: [{
      label: 'Stacked A1',
      data: [{
        x: 'Mon',
        y: 10
      }, {
        x: 'Tue',
        y: 12
      }, {
        x: 'Wed',
        y: 8
      }, {
        x: 'Thu',
        y: 14
      }],
      backgroundColor: 'rgba(255, 99, 132, 0.6)',
      stack: 'stack1',
      barPercentage: 1.0,
      categoryPercentage: 0.8,
    },
    {
      label: 'Stacked A2',
      data: [{
        x: 'Mon',
        y: 15
      }, {
        x: 'Tue',
        y: 18
      }, {
        x: 'Wed',
        y: 12
      }, {
        x: 'Thu',
        y: 20
      }],
      backgroundColor: 'rgba(255, 159, 64, 0.6)',
      stack: 'stack1',
      barPercentage: 1.0,
      categoryPercentage: 0.8,
    },
    {
      label: 'Narrow B',
      data: [{
        x: 'Mon',
        y: 20
      }, {
        x: 'Tue',
        y: 18
      }, {
        x: 'Wed',
        y: 22
      }, {
        x: 'Thu',
        y: 16
      }],
      backgroundColor: 'rgba(75, 192, 192, 0.6)',
      stack: 'stack2',
      barPercentage: 1, // ~1/6th width
      categoryPercentage: 0.2,
    },
    {
      label: 'Normal C',
      data: [{
        x: 'Mon',
        y: 25
      }, {
        x: 'Tue',
        y: 30
      }, {
        x: 'Wed',
        y: 28
      }, {
        x: 'Thu',
        y: 32
      }],
      backgroundColor: 'rgba(54, 162, 235, 0.6)',
      stack: 'stack3',
      barPercentage: 1.0,
      categoryPercentage: 0.8
    }
  ]
};

const config = {
  type: 'bar',
  data: data,
  options: {
    responsive: true,
    plugins: {
      legend: {
        display: false
      },
    },
    scales: {
      x: {
        stacked: true,
        ticks: {
          display: true
        },
      },
      y: {
        stacked: false,
        beginAtZero: true,
      }
    }
  }
};

new Chart(ctx, config);
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="capacityOverviewChart">


Solution

  • Adjust the inflatAmount value to play with the gap between the bars.

    options: {
        inflateAmount: 8, // Adjust this value 
        responsive: true,
        plugins: {
          legend: {
            display: false
          },
        },
    

    You may also need to change barPercentage according to the change of inflatAmount to make it look better.