2

I'm using chartjs 2, and I'm trying to disable the grid lines on xAxis and enable grid lines on yAxis and make them dashed.

I have achieved this functionality by adding this to my Line graph config;

scales: {
    xAxes: [{
        display: true,
        gridLines: {
            display: false,
        }
    }],
    yAxes: [{
        display: true,
        gridLines: {
            display: true,
            borderDash: [2],
            borderDashOffset: [2],
            color: 'rgba(0, 0, 0, 0.04)',
            drawBorder: false,
            drawTicks: false,
        }
    }]
}

However, when I do this, it randomly adds another axis to my chart with completely bogus values. I want to remove this axis and keep the original but also keep the gridLines config.

enter image description here

Borassign
  • 621
  • 2
  • 7
  • 16

1 Answers1

3

You can set the defaults for this. You can set it in the scale default so it does it for all the chart types and scales. If you specifically want to hide the X axis gridLines only you need to set it on chart type level.

Chart.defaults.scale.gridLines.display = false // hides all the gridLines in all charts for all axes
Chart.defaults.line.scales.xAxes[0].gridLines = {
  display: false
} // Hides only the X axes gridLines in all line charts

var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderWidth: 1
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderWidth: 1
      }
    ]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          reverse: false
        }
      }]
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
</body>
LeeLenalee
  • 27,463
  • 6
  • 45
  • 69
  • Chart.defaults.line.scales.xAxes[0] only has variables 'id' and 'type' for me. Doesn't have 'gridLines' so setting that default isn't possible. Any ideas why these wouldn't be available for me? – Borassign Nov 02 '21 at 14:07
  • 1
    it also isnt available in my stack snippet thats why I set the gridLines to an object because if I would try to set it like this: `Chart.defaults.line.scales.xAxes[0].gridLines.display = false` it cant do that since gridLines is undefined. Thats why I do `.gridLines = {}` so it makes the property on the object – LeeLenalee Nov 02 '21 at 14:09