[Chartjs]-ChartJS How to set max labels for X axis?

1👍

You can do it by defining the min and max values under the time key.

If min or max is defined, this will override the data minimum or maximum respectively. See docs for more info.

chartHour.config.options.scales.xAxes[0] = {
  type: "time",
  time: {
    min: "2017-01-01",
    max: "2017-12-01",
    displayFormats: {
      day: "MMM YY"
    }
  }
};

See working example below.

const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const years = [2016, 2017, 2018];

const labels = [];
const dataSet = [];
years.forEach((year, index) => {
  months.forEach((month, monthIndex) => {
    const date = moment(`${month} ${year}`, "MMM YYYY").format('YYYY-MM-DD');
    labels.push(date);
    dataSet.push({
      x: date,
      y: (monthIndex + 12) * (index + 1)
    });
  });
});

var data = {
  labels: labels,
  datasets: [{
    pointRadius: 0,
    label: "Positive",
    lineTension: 0,
    data: dataSet,
    borderWidth: 1,
    backgroundColor: "rgba(0, 255, 0, 0.5)"
  }]
};
var options = {
  scales: {
    xAxes: [{
      type: "time",
      distribution: 'series',
      time: {
        min: "2017-01-01",
        max: "2017-12-01",
        displayFormats: {
          day: 'MMM YY'
        }
      },
      ticks: {
        source: "labels"
      },
      gridLines: {
        display: false
      }
    }]
  }
};

var ctx = document.getElementById("myChart").getContext("2d");

var myBarChart = new Chart(ctx, {
  type: "bar",
  data: data,
  options: options
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>
<canvas id="myChart" width="300" height="100"></canvas>

Leave a comment