Search code examples
javascriptchart.jslinechartreact-chartjs

How to display grid lines (without showing label) between each ticks?


enter image description here

I'm using Chart.js 2 (React-chart-js 2) to display a line chart.

Does anyone have any reference to keeping the vertical gridline between each displayed label?

It seems like the vertical gridline only showing on each displayed label.


Solution

  • You can make use of the scriptable options for this, see example that hides every second label, you can adjust it to hide a bigger step if you want.

    Example:

    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: {
          x: {
            ticks: {
              callback: function(val, index) {
                return index % 2 === 0 ? this.getLabelForValue(val) : '';
              }
            }
          }
        }
      }
    }
    
    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/3.0.0/chart.js"></script>
    </body>