ChartJS将每月标签更改为时间/日期

时间:2018-12-10 07:04:42

标签: javascript chart.js

index.php

  <!DOCTYPE html>
<html>
<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.0/Chart.bundle.min.js"></script>
</head>
<canvas id="myChart"></canvas>
<script  src="assets/js/script-java.js"></script>
</body>
</html>

script-java.js

var ctx = document.getElementById('myChart').getContext('2d');

var chart = new Chart(ctx, {
  // The type of chart we want to create
  type: 'line',

  // The data for our dataset
  data: {
      labels: ["January","Fberuary","March"],
      datasets: [{
          label: "My First dataset",
          backgroundColor: 'rgb(255, 99, 132)',
          borderColor: 'rgb(255, 99, 132)',
          data: [120, 10, 5, 2, 20, 30, 45],

      }]
  },

  // Configuration options go here
  options: {}
});

输出: enter image description here

这是代码,如您所见,我的标签是“每月”名称,如何用时间/数据替换它?我想要实现的目标就像股票市场图表一样,您可以在其中看到数据输入的日期和时间。

谢谢

编辑:我刚刚看到一个文档:https://www.chartjs.org/docs/latest/axes/cartesian/time.html

我尝试过,代码脚本现在是:

var ctx = document.getElementById('myChart').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: "My First dataset",
          backgroundColor: 'rgb(255, 99, 132)',
          borderColor: 'rgb(255, 99, 132)',
          data: [120, 10, 5, 2, 20, 30, 45],

      }]

  },

  // Configuration options go here
    options: {
        scales: {
            xAxes: [{
                type: 'time',
                time: {
                    displayFormats: {
                        quarter: 'MMM YYYY'
                    }
                }
            }]
        }
    }
});

但是现在什么也没显示。

1 个答案:

答案 0 :(得分:0)

var ctx = document.getElementById('myChart').getContext('2d');

var chart = new Chart(ctx, {
type: 'line',

// The data for our dataset
data: {
    datasets: [{
        label: "My First dataset",
        backgroundColor: 'rgb(255, 99, 132)',
        borderColor: 'rgb(255, 99, 132)',
        // data : [10,20]
        data: [{x: new Date(), y:15},{x: moment().add(10,'days'), y:50},
        {x : moment().add(15,'days'), y:20}],

    }]

},

// Configuration options go here
  options: {
      scales: {
          xAxes: [{
              type: 'time',
              time: {
                // unit: 'month',
                  displayFormats: {
                      quarter: 'MMM YYYY'
                  }
              }
          }]
      }
  }
});