ChartJS 2 How to globally remove xAxis gridLines?

Viewed 292

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

1 Answers

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>

Related