1

How can I add white spaces/margin between bars with Chart.js 3.0 ? I didn't find anything to process like the image

What I want

My code looks like this and makes this : What I have

datasets: [{
                categoryPercentage: 1.0,
                barPercentage: 0.8,
            }]
        },
    options: {
            onHover() {},
            indexAxis: 'y',
            maintainAspectRatio: false,
     }

full code here : https://codepen.io/mateofaivre/pen/zYdYgmB

mateofaivre
  • 21
  • 1
  • 5

2 Answers2

3

You should set the categoryPercentage to lower value like 0.8 and barPercentage to 1.

Graphical info about categoryPercentage vs barPercentage:

// categoryPercentage: 1.0
// barPercentage: 1.0
Bar:        | 1.0 | 1.0 |
Category:   |    1.0    |
Sample:     |===========|

// categoryPercentage: 1.0
// barPercentage: 0.5
Bar:          |.5|  |.5|
Category:  |      1.0     |
Sample:    |==============|

// categoryPercentage: 0.5
// barPercentage: 1.0
Bar:             |1.0||1.0|
Category:        |   .5   |
Sample:     |==================|

EDIT:

You can get the bar width from the metasets of the chart and use that to draw it on the chart like so:

const plugin = {
  id: 'background',
  beforeDraw: (chart, args, opts) => {
    if (!opts.color) {
      return;
    }

    const {
      ctx,
      chartArea,
      _metasets
    } = chart;

    ctx.fillStyle = opts.color;

    _metasets.forEach(meta => {
      meta.data.forEach(data => {
        if (data.horizontal) {
          ctx.fillRect(chartArea.left, (data.y - (data.height / 2)), chartArea.width, data.height)
        } else {
          ctx.fillRect((data.x - (data.width / 2)), chartArea.top, data.width, chartArea.height)
        }
      })
    });
  }
}

Chart.register(plugin);

var colors = [];
for (var i = 0; i < 5; i++) {
  colors.push('#5671DB');
}
var config = {
  type: 'bar',
  data: {
    labels: ['Commerce, vente', 'Transport', 'Bureautique', 'Accueil', 'Santé', 'Secrétariat', 'Nettoyage', 'Sécurité', 'Mécanique', 'Agro-alimentaire'],
    datasets: [{
      data: [23.8, 17.7, 13, 9.5, 7.8, 7, 5.5, 5, 4.5, 3.5],
      backgroundColor: colors,
      hoverBackgroundColor: colors,
      borderColor: colors,
    }],
  },
  options: {
    onHover() {},
    indexAxis: 'y',
    barPercentage: 0.8,
    //barThickness: 60,
    // maxBarThickness: 60,
    categoryPercentage: 1.0,
    maintainAspectRatio: true,
    responsive: true,
    plugins: {
      background: {
        color: '#CDECEF'
      },
      title: {
        display: false,
        text: "Les 10 principaux domaines d'emploi",
        align: 'start',
        fullSize: true,
        color: '#324488',
        font: {
          size: 24,
          family: 'Arial',
        }
      },
      legend: {
        display: false
      },
      tooltip: {
        backgroundColor: 'rgba(255,255,255,0)',
        displayColors: false,
        titleFont: {
          size: 0,
        },
        titleMarginBottom: 0,
        titleSpacing: 0,
        bodyFont: {
          size: 25,
          weight: 700
        },
        xAlign: 'right',
        callbacks: {
          label: (item) => (`${item.parsed.x} %`),
        },
      },
    },
    scales: {
      y: {
        beginAtZero: true,
        ticks: {
          color: "#34478B",
          font: {
            size: 18,
          },
          stepSize: 1,
          beginAtZero: true
        },
      },
      x: {
        ticks: {
          color: "#25C8C9",
          font: {
            size: 14
          },
          stepSize: 1,
          beginAtZero: true
        },

      }
    }
  },
};


var ctx = document.getElementById('myChart').getContext('2d');
new Chart(ctx, config);
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="myChart"></canvas>

codePen

LeeLenalee
  • 27,463
  • 6
  • 45
  • 69
  • Thanks, but It not makes what I want :/ – mateofaivre Oct 11 '21 at 07:30
  • 1
    Please share your whole code then because if you put it correctly it should work – LeeLenalee Oct 11 '21 at 07:31
  • https://codepen.io/mateofaivre/pen/zYdYgmB – mateofaivre Oct 11 '21 at 09:40
  • 1
    Next time please include your code in your question because what you want is not margin between bars, you want gaps in the background you are drawing using a custom plugin so no way people could help you – LeeLenalee Oct 11 '21 at 12:08
  • and if i don't use a plugin for the background it's possible ? – mateofaivre Oct 11 '21 at 12:46
  • 1
    As you can see in my live example with a plugin its possible, otherwise you will need to use an extra dataset and make the data stacked but that will be more config work since you need to calculate all bar heights yourself and make sure the max of the scale is set correctly – LeeLenalee Oct 11 '21 at 12:54
0

If reducing the bar size is not a problem you could add barPercentage to your options.

Like this:

const config = {
  type: 'bar',
  data,
  options: {
    indexAxis: 'y',
    barPercentage: 0.8
  }
};

Bar Chart | Charts.js

Irfan Bilir
  • 73
  • 10