Chartjs-How can I display fixed labels on X-axis while having data on that axis?

1๐Ÿ‘

โœ…

I advise to convert your chart to xy chart, set axis options and customize tooltips

var ctx = document.getElementById("myChart").getContext('2d');
var precision = 0;
var data = getData();

var myChart = new Chart(ctx, {
  type:"scatter",
    data: {
        datasets: [{
            label: 'grades',
            data: data,
            fill: false,
            pointRadius: 0,
            pointHitRadius: 3
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true,
                    max:6
                }
            }],
            xAxes: [{
                ticks: {
                    beginAtZero:true,
                    max:35,
                    stepSize: 1,
                    callback: function(value){
                      if (value < 5){
                        return value;
                      } else {
                        if (value% 5 === 0){
                          return value;
                        }
                      }
                    }
                }
            }]
        },
        tooltips: {
            callbacks: {
                label: function(tooltipItem, data) {
                    var label = [
                    'X: ' + tooltipItem.xLabel.toFixed(precision),
                    'Y: ' + tooltipItem.yLabel.toFixed(precision)
                    ];
                    return label;
                }
            }
        }
    }
});

function getData(){
  var step = 10**-precision;
  var arr = [];
  for (var i=0; i<=6; i+=step){
    arr.push({y: i, x: 35*i/6})
  }
  return arr;
}

setTimeout(function(){
    precision = 1;
    myChart.data.datasets[0].data = getData();
    myChart.update();

}, 2000)
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.js"></script>
<canvas id="myChart" width="100" height="100"></canvas>

Leave a comment