skip to Main Content

enter image description here

How to fix these spacing between bars ? when i have few data its become long width spacing.

What i want is

  1. fixed bar size
  2. fixed spacing between bars
  3. fit-content of canvas width so when there just a few data, its become compact and if its have much data , its become long

Note: My chart.js version is 4.4.0

2

Answers


  1. To adjust the spacing between bars in a chart created with Chart.js, you generally have to tweak a few configuration options related to the chart’s scales and dataset. The spacing can be influenced by the barThickness, categoryPercentage, and barPercentage properties.

    Login or Signup to reply.
  2. Look at the demo of this sample chart as it will be similar in your code I am guessing.

    var ctx = document.getElementById(‘myChart’).getContext(‘2d’);

    var data = {
        labels: ['January', 'February', 'March', 'April', 'May'],
        datasets: [{
            label: 'Sample Data',
            data: [10, 20, 30, 40, 50],
            backgroundColor: 'rgba(255, 99, 132, 0.5)',
            borderColor: 'rgba(255, 99, 132, 1)',
            borderWidth: 1
        }]
    };
    
    var options = {
        layout: {
            padding: {
                left: 10,
                right: 10,
                top: 10,
                bottom: 10
            }
        },
        scales: {
            x: {
                grid: {
                    display: false
                }
            },
            y: {
                grid: {
                    display: false
                },
                beginAtZero: true
            }
        },
        plugins: {
            legend: {
                display: true,
                position: 'top',
            }
        },
        maintainAspectRatio: false
    };
    
    var myChart = new Chart(ctx, {
        type: 'bar',
        data: data,
        options: options
    });
    

    And now your requirements will fit in as per three things below:

    • layout.padding is set to add some padding around the chart area.
    • scales.x.grid.display and scales.y.grid.display are set to false to
      hide the grid lines.
    • maintainAspectRatio is set to false to allow the chart to adjust its
      size based on the container width.

    Hope this helps. Let me know how it goes.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search