Search code examples
reactjschart.jsreact-chartjs-2

How to add space to start and end of x-axis in chartjs on react....i have tried using "offset:true" but it does not work if the label are more


Currently it look like this - https://mm5qkg.csb.app/ --- sandbox

Using "offset:true" is working if the labels are less but it start decreasing as the label quantity start increasing

I tried many solution but it didn't work

I am using it with react-chartjs-2


Solution

  • Your x-axis could be defined of type: 'linear' and the data as an array of objects, having an x and y property each. Then you can use ticks.min and ticks.max to define the range that should be displayed in the chart.

    const values = [0, 53, 85, 0, 0, 65, 5, 18, 2, 44, 2, 2, 42, 44, 21, 55];
    
    const valueXStart = 4;
    
    const options = {
      scales: {
        xAxes: [
          {
            type: 'linear',
            ticks: {
              min: 3.8,
              max: 7,
              stepSize: 0.1
            }
          }
        ]
      }
    };
    
    const data = {
      datasets: [
        {
          label: "First dataset",
          data: values.map((v, i) => ({ x: valueXStart + i * 0.1, y: v })),
          ...
        }
      ]
    };
    

    Please take a look at your amended CodeSandbox and see how it works.