Chartjs-Is there any way to create a gap in between the stacked vertical bars in Chart.JS?

0👍

One possible approach is a tricky, dirt workaround: add a fake dataset between those 2 and set the background color to the same of chart background (prolly white). And ofc hide fake dataset in legend and tooltips.

const data = {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
datasets: [
    {
        label: 'Retained',
        data: [62,68,74,80,66,84],
        backgroundColor: '#759BE4',
        order: 3,
        stack: 'stack1'
    },
    {
        label: 'placeholder',
        data: [1,1,1,1,1,1],//the more this is big, the more space between bars
        backgroundColor: 'white',//Same as background
        order: 3,
        stack: 'stack1'
    },
    {
      label: 'Expired',
      data: [5,3,7,9,2,4],
      backgroundColor: '#307472',
      order: 3,
      borderRadius: 4,
      stack: 'stack1'
    }
]
}

const config = {
type: 'bar',
data: data,
options: {
    scales: {
        x: {
            stacked: true
        },
        y: {
            stacked: true
        }
    },
    plugins : {
        legend: {
            labels: {
                filter: function(label) {
                    if (label.text === 'placeholder') return false;//label of fake dataset
                    else return true;
                }
            }
        },
        tooltip: {
            filter: function (tooltipItem) {
                const datasetIndex = tooltipItem.datasetIndex;

                if (datasetIndex === 1) { //index of fake dataset
                    return false;
                } else {
                    return true;
                }
            }
        }
    }
}};

const reportOutput = new Chart(
document.getElementById('chart_display'),
  config
);

Hope it helps.

Leave a comment