首页 > 解决方案 > 如何在 x 轴上制作带有动态月份的 Chart.js

问题描述

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

但我有两个问题:

  1. 线条没有显示在我的图表上
  2. x 轴只显示第一个月和最后一个月,中间没有月份。

这是我在油漆中制作的一个示例,以展示我想要实现的目标:

在此处输入图像描述

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

/* 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>

标签: javascriptchart.js

解决方案


使用 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+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>


推荐阅读