如何使Chart.js在x轴上具有动态月份

问题描述 投票:0回答:1

[我正在尝试使用动态x轴制作Chart.js,并始终将接下来的7个月用作x轴的刻度。

但是我有两个问题:

  1. 这些线未显示在我的图形上
  2. x轴仅显示第一个月和最后一个月,中间没有一个月。

这是我在绘画中制作的示例,以显示我要实现的目标:

enter image description here

这是我到目前为止的代码:

/* 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>
javascript chart.js
1个回答
0
投票

使用moment.js库,您可以查看数组的长度,并从开始的月份生成月份,然后将其作为标签使用

/* 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 + 3).date(0).startOf('month'))
}
var 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]
  }]
};

var options = {
  scales: {
    xAxes: [{
      type: 'time',
      gridLines: {
        display: true
      },
      time: {
        minUnit: 'month'
      }
    }]
  }
};
var chart = new Chart(ctx, {
  type: 'line',
  data: data,
  options: options

});
<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>
© www.soinside.com 2019 - 2024. All rights reserved.