TinyTiger
TinyTiger

Reputation: 2053

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

I'm trying to make a Chart.js with a dynamic x-axis that will always use the next 7 months as the ticks for the x-axis.

But I'm having two problems:

  1. The lines are not showing on my graph
  2. The x-axis is only showing the first and last month, none of the months in-between.

Here is an example I made in paint to show what I'm trying to achieve:

enter image description here

And here is the code I have so far:

/* Build the charts */
var ctx = document.getElementById('ROIchart').getContext('2d');
var chart = new Chart(ctx, {
  // The type of chart we want to create
  type: 'line',

  // The data for our dataset
  data: {
    datasets: [{
      label: 'Paid Search and Leads',
      backgroundColor: 'red',
      borderColor: 'red',
      data: [10, 10, 10, 10, 10, 10, 10],
    }, {
      label: 'SEO and Content',
      backgroundColor: 'green',
      borderColor: 'green',
      data: [0, 2, 8, 21, 57, 77, 100],
      fill: true,
    }]
  },

  // Configuration options go here
  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>
<canvas id="ROIchart"></canvas>

Upvotes: 0

Views: 4488

Answers (1)

HERRERA
HERRERA

Reputation: 251

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>

Upvotes: 2

Related Questions