代码之家  ›  专栏  ›  技术社区  ›  TinyTiger

如何制作图表。x轴上有动态月份的js

  •  0
  • TinyTiger  · 技术社区  · 6 年前

    我想做一张图表。js具有动态x轴,将始终使用未来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>
    0 回复  |  直到 6 年前
        1
  •  2
  •   HERRERA    6 年前

    就在此时此刻。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>