How to add space between Legend text and chart in ChartJs v4

112 Views Asked by At

I'm using Chart.js version 4.4.1, and I want to increase the space between the legend and the chart.

I need a solution for barchart. I'm sharing the code for the bar chart. I've checked several posts, but I couldn't find a solution for the latest version.

Below is my code:

new Chart('myChart', {
  type: 'bar',
  plugins: [{
    afterInit: chart => {
      let dataset = chart.data.datasets[0];
      chart.data.datasets = chart.data.labels.map((l, i) => ({
        label: l,
        data: [{ x: dataset.data[i], y: i }],
        backgroundColor: dataset.backgroundColor[i],
        categoryPercentage: 1
      }));
      chart.data.labels = undefined;
    },
    beforeLayout: chart => {
      chart.options.scales.y1.labels = chart.data.datasets.filter((ds, i) => !chart.getDatasetMeta(i).hidden).map(ds => ds.label);
    }
  }],
  data: {     
    labels: ['Red', 'Blue', 'Green', 'Teal', 'Yellow', 'Purple', 'Orange', 'Black'],
    datasets: [{
      data: [123, 321, 213, 111, 222, 333, 234, 444],
      backgroundColor: ['Red', 'Blue', 'Green', 'Teal', 'Yellow', 'Purple', 'Orange', 'Black']
    }]
  },
  options: {
    indexAxis: 'y',
    maintainAspectRatio: false,
    plugins: {
        datalabels: {
        color: 'white',
        formatter: function(value, context) {
                    return value.x;
                },
      },
      legend: {
        position: 'top'
      },
      tooltip: {
        callbacks: {
          title: () => null
        }
      }
    },
      scales: {
          x: {
              title: {
                  display: true,
                  text: 'xAxis'
              }

          },
          y: {
                  display: false,
          },
          y1: {
              title: {
                  display: true,
                  text: 'yAxisLabel'
              },
              offset: true
          }
      }
  }, 
 
});
0

There are 0 best solutions below