如何在 x 轴上制作带有动态月份的 Chart.js

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

但我有两个问题:

  1. 线条没有显示在我的图表上

  2. x 轴只显示第一个月和最后一个月,中间没有月份。

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

http://img3.mukewang.com/62d8b41600014f1507820555.jpg

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


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


慕桂英3389331
浏览 125回答 1
1回答

临摹微笑

使用 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++) {&nbsp; months.push(moment().year(2020).month(i+1).date(0).startOf('month'))}var chart = new Chart(ctx, {&nbsp; type: 'line',&nbsp; data: {&nbsp; &nbsp; labels: months,&nbsp; &nbsp; datasets: [{&nbsp; &nbsp; &nbsp; label: 'Paid Search and Leads',&nbsp; &nbsp; &nbsp; backgroundColor: 'red',&nbsp; &nbsp; &nbsp; borderColor: 'red',&nbsp; &nbsp; &nbsp; data: array1,&nbsp; &nbsp; }, {&nbsp; &nbsp; &nbsp; label: 'SEO and Content',&nbsp; &nbsp; &nbsp; backgroundColor: 'green',&nbsp; &nbsp; &nbsp; borderColor: 'green',&nbsp; &nbsp; &nbsp; data: [0, 2, 8, 21, 57, 77, 100],&nbsp; &nbsp; &nbsp; fill: true,&nbsp; &nbsp; }]&nbsp; },&nbsp; options: {&nbsp; &nbsp; responsive: true,&nbsp; &nbsp; scales: {&nbsp; &nbsp; &nbsp; xAxes: [{&nbsp; &nbsp; &nbsp; &nbsp; type: 'time',&nbsp; &nbsp; &nbsp; &nbsp; time: {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; unit: 'month'&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; }]&nbsp; &nbsp; }&nbsp; }});<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>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript