Chart.js - scaleType='date' 不工作

Chart.js - scaleType='date' not working

使用 Chart.js,我试图让 x 轴(和工具栏)显示日期,但我只能得到显示为 x 轴标签的大整数。我已经比较了文档中的示例所做的事情,但我没有看到它在做什么,而我没有。有人可以帮忙吗?

这是我创建的小示例,显示它不起作用。 (顺便说一句 - 作为附带问题,请注意,如果 RED 线的颜色拼写为 Red 而不是 red,则该线看起来很正常,但工具提示不再适用于该线) https://plnkr.co/edit/CKUf4zFC1vhe3VNUF5Lf?p=preview

javascript for the above plunker example is below
----------------------------------------------------
<!DOCTYPE html>
<html>
<head>
</head>

<body>
  <div>
    <canvas id="canvas"></canvas>

    <script>
      var chartData = {
        datasets: [{
          borderColor: 'Red',
          label: 'Capital R in borderColor, tooltips dont work',
          data: [{
            x: new Date('2011-04-11T11:45:00'),
            y: 25
          }, {
            x: new Date('2011-04-11T12:51:00'),
            y: 28
          }, {
            x: new Date('2011-04-11T14:10:00'),
            y: 22
          }, {
            x: new Date('2011-04-11T15:15:00'),
            y: 18
          }]
        }, {
          borderColor: 'green',
          label: 'borderColor all lower case, tooltips now work',
          data: [{
            x: new Date('2011-04-11T11:45:00'),
            y: 15
          }, {
            x: new Date('2011-04-11T12:51:00'),
            y: 18
          }, {
            x: new Date('2011-04-11T14:10:00'),
            y: 12
          }, {
            x: new Date('2011-04-11T15:15:00'),
            y: 8
          }]
        }, ]
      };


      window.onload = function() {

        var ctx = document.getElementById("canvas").getContext("2d");
        window.myScatterxx = Chart.Scatter(ctx, {
          data: chartData,
          scaleType: 'date',
          options: { title: { display: true, text: "scaleType='date' isn't working", fontSize:36} },
        });
      };
    </script>


    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.1/Chart.min.js">
    </script>

</body>
</html>

首先,由于文档很乱,您不知道如何创建时间刻度图表我并不感到惊讶。实际调用如下:

window.myScatterxx = Chart.Scatter(ctx, {
    data: chartData,
    options: {
        title: {
            display: true,
            text: "it is now working",
            fontSize: 36
        },
        scales: {
            xAxes: [{
                // This is the important part
                type: "time",
            }]
        }
    },
});


现在您有了正确的语法,您还需要导入正确的库。正如我在您提供的代码中看到的那样,您导入了 Chart.min.js,但您需要更多,因为您知道如何使用时间元素。

您可以:


最后,我还注意到在您的代码中,您在显示红色数据集的工具提示时遇到了问题。这是因为你定义它的颜色为Red。将其更改为 red,工具提示将再次起作用:

datasets: [{
    borderColor: 'red',
    label: 'Capital R in borderColor, tooltips now work',
    data: [
        // ...
    ]
}]

您可以实时查看所有这些修复 in this jsFiddle,这是最终结果: