How to reduce spaces between grids for graph in chart.js?

Member

by deron , in category: Javascript , 2 months ago

How to reduce spaces between grids for graph in chart.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by lindsey.homenick , 2 months ago

@deron 

To reduce the spaces between grids in a chart created using Chart.js library, you can customize the scales option of the chart configuration. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
var chartOptions = {
  scales: {
    x: {
      grid: {
        display: true,
        borderWidth: 1,
        color: 'rgba(0, 0, 0, 0.1)',
        drawBorder: false,
        drawOnChartArea: false,
        drawTicks: false,
        borderDash: [3],
        tickMarkLength: 0,
        offset: true // Enable this option to reduce the space between grid lines
      }
    },
    y: {
      grid: {
        display: true,
        borderWidth: 1,
        color: 'rgba(0, 0, 0, 0.1)',
        drawBorder: false,
        drawOnChartArea: false,
        drawTicks: false,
        borderDash: [3],
        tickMarkLength: 0,
        offset: true // Enable this option to reduce the space between grid lines
      }
    }
  }
};

// Construct chart dataset and labels
var chartData = {...};

// Create the chart
var myChart = new Chart(ctx, {
  type: 'line',
  data: chartData,
  options: chartOptions
});


You can adjust the offset option in the grid object to control the spacing between the grid lines. Setting it to false will result in no space between the grid lines, while setting it to true will introduce some space between the grid lines.


Feel free to adjust other options within the grid object as well to further customize the appearance of the grid lines.