Chartjs-How to make Chart.js with dynamic months on x-axis

2👍

With the moment.js library, you can look at the length of your array, and from a starting month generate the months, and then put them as labels

/* Build the charts */
var ctx = document.getElementById('ROIchart').getContext('2d');
var array1 = [10, 10, 10, 10, 10, 10, 10];
var months = []
for (let i = 0; i < array1.length; i++) {
  months.push(moment().year(2020).month(i+1).date(0).startOf('month'))
}
var chart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: months,
    datasets: [{
      label: 'Paid Search and Leads',
      backgroundColor: 'red',
      borderColor: 'red',
      data: array1,
    }, {
      label: 'SEO and Content',
      backgroundColor: 'green',
      borderColor: 'green',
      data: [0, 2, 8, 21, 57, 77, 100],
      fill: true,
    }]
  },
  options: {
    responsive: true,
    scales: {
      xAxes: [{
        type: 'time',
        time: {
          unit: 'month'
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
<canvas id="ROIchart"></canvas>

Leave a comment