为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕桂英3389331 2022-07-21 10:03:28
我正在尝试制作一个带有动态 x 轴的 Chart.js,它将始终使用接下来的 7 个月作为 x 轴的刻度。但我有两个问题:线条没有显示在我的图表上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>
查看完整描述

1 回答

?
临摹微笑

TA贡献1982条经验 获得超2个赞

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


查看完整回答
反对 回复 2022-07-21
  • 1 回答
  • 0 关注
  • 123 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号