Javascript Chart.js 使用日期创建折线图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47875045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:58:11  来源:igfitidea点击:

Chart.js creating a line graph using dates

javascriptdatechart.jsejs

提问by Jonathan Woollett-light

I can't seem to get Chart.js to work with dates. I have tried quite a few different methods:

我似乎无法让 Chart.js 处理日期。我尝试了很多不同的方法:

let examChart = document.getElementById("examChart").getContext("2d");
let examLineChart = new Chart(examChart, {
    type: "line",
    data: [
            { t: new Date("2015-3-15 13:3"), y: 12 },
            { t: new Date("2015-3-25 13:2"), y: 21 },
            { t: new Date("2015-4-25 14:12"), y: 32 }
    ],
    options: {
        label: "placeholder"
    }
});

And:

和:

let examChart = document.getElementById("examChart").getContext("2d");
let examLineChart = new Chart(examChart, {
    type: "line",
    data: [
            { t: "2015-3-15 13:3", y: 12 },
            { t: "2015-3-25 13:2", y: 21 },
            { t: "2015-4-25 14:12", y: 32 }
    ],
    options: {
        label: "placeholder"    
    }
});

And:

和:

let examChart = document.getElementById("examChart").getContext("2d");
let examLineChart = new Chart(examChart, {
    type: "line",
    data: [
            { t: "Sun Mar 15 2015 12:03:45 GMT+0000 (GMT Standard Time)", y: 12 },
            { t: "Wed Mar 25 2015 12:02:15 GMT+0000 (GMT Standard Time)", y: 21 },
            { t: "Sat Apr 25 2015 13:12:30 GMT+0100 (GMT Daylight Time)", y: 32 }
    ],
    options: {
        label: "placeholder"    
    }
});

To cover just a few of my attempts, I just can't seem to get how to set dates properly even after reading the documentation (http://www.chartjs.org/docs/latest/axes/cartesian/time.html) (they don't actually give an example)

为了涵盖我的一些尝试,即使在阅读文档(http://www.chartjs.org/docs/latest/axes/cartesian/time.html)后,我似乎也无法正确设置日期(他们实际上并没有给出一个例子)

The HTML being used:

正在使用的 HTML:

<div class="container">
    <canvas id="examChart"></canvas>
</div>

I just have no idea, although I imagine this is a rather simple problem, any help would be greatly appreciated.

我只是不知道,虽然我认为这是一个相当简单的问题,但任何帮助将不胜感激。

回答by Ramiz Wachtler

You have to move your data within a dataset. If you take a look at the usage manual, a datasetsarray is used. The "hint"for datasets within the docs for timeis also not that obvious (See headline).

您必须在dataset. 如果您查看使用手册datasets则会使用数组。文档中数据集的“提示”时间也不是那么明显(见标题)。

See the snippet below:

请参阅下面的片段:

I just copied the basic usage example and inserted the data from your first attempt (+ added few labels)

我只是复制了基本用法示例并插入了您第一次尝试的数据(+ 添加了几个标签)

UPDATE 18.03.2020

更新 18.03.2020

I've updated the snippet to use Chart.js 2.8.0and added following code, as suggested in the comment by @Erik

我已经更新了代码片段以使用 Chart.js2.8.0并添加了以下代码,如@Erik的评论中所建议的

options: {
    scales: {
      xAxes: [{
        type: 'time'
      }]
    }
  }

var ctx = document.getElementById("examChart").getContext("2d");

var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: [new Date("2015-3-15 13:3").toLocaleString(), new Date("2015-3-25 13:2").toLocaleString(), new Date("2015-4-25 14:12").toLocaleString()],
    datasets: [{
      label: 'Demo',
      data: [{
          t: new Date("2015-3-15 13:3"),
          y: 12
        },
        {
          t: new Date("2015-3-25 13:2"),
          y: 21
        },
        {
          t: new Date("2015-4-25 14:12"),
          y: 32
        }
      ],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
        'rgba(75, 192, 192, 0.2)',
        'rgba(153, 102, 255, 0.2)',
        'rgba(255, 159, 64, 0.2)'
      ],
      borderColor: [
        'rgba(255,99,132,1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
        'rgba(75, 192, 192, 1)',
        'rgba(153, 102, 255, 1)',
        'rgba(255, 159, 64, 1)'
      ],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      xAxes: [{
        type: 'time'
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.js"></script>
<div class="container">
  <canvas id="examChart"></canvas>
</div>

回答by SoiBoi

Building on what @RamizWachtler has answered, you can add to the options section of the chart to scale the times out properly. I'll note that this doesn't seem to work with Charts.js 2.3. Added a working snippet that uses the latest Charts.js version as of April 2019.

根据@RamizWachtler 的回答,您可以添加到图表的选项部分以正确缩放超时。我会注意到这似乎不适用于 Charts.js 2.3。添加了使用截至 2019 年 4 月的最新 Charts.js 版本的工作片段。

Additionally I've changed the time formatting to be ISO8601 compliant.

此外,我已将时间格式更改为符合 ISO8601。

var chart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: {
        scales: {
            xAxes: [{
                type: 'time',
                distribution: 'linear'
            }]
        }
    }
});

Source - https://www.chartjs.org/docs/latest/axes/cartesian/time.html

来源 - https://www.chartjs.org/docs/latest/axes/cartesian/time.html

var ctx = document.getElementById("examChart").getContext("2d");

var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ["2015-03-15T13:03:00Z", "2015-03-25T13:02:00Z", "2015-04-25T14:12:00Z"],
    datasets: [{
      label: 'Demo',
      data: [{
          t: "2015-03-15T13:03:00Z",
          y: 12
        },
        {
          t: "2015-03-25T13:02:00Z",
          y: 21
        },
        {
          t: "2015-04-25T14:12:00Z",
          y: 32
        }
      ],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
        'rgba(75, 192, 192, 0.2)',
        'rgba(153, 102, 255, 0.2)',
        'rgba(255, 159, 64, 0.2)'
      ],
      borderColor: [
        'rgba(255,99,132,1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
        'rgba(75, 192, 192, 1)',
        'rgba(153, 102, 255, 1)',
        'rgba(255, 159, 64, 1)'
      ],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      xAxes: [{
        type: 'time',
        distribution: 'linear'
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0-rc.1/Chart.bundle.js"></script>
<div class="container">
  <canvas id="examChart"></canvas>
</div>

回答by user10408

when using time, you have to use UTC time, as your local time is added(australia +10 hours / 36000 secs) so every country has a different time zone. the key is to use moment.utc in any conversion of time 0 seconds = moment.utc('1970-01-01 00:00:00')

使用时间时,您必须使用 UTC 时间,因为添加了本地时间(澳大利亚 +10 小时 / 36000 秒),因此每个国家/地区都有不同的时区。关键是在任何时间转换中使用 moment.utc 0 seconds = moment.utc('1970-01-01 00:00:00')

use moment.utc('1970-01-01').add(3600, 'seconds')to add a value and then from y-axis values or tool tip items, you have to reference

用于moment.utc('1970-01-01').add(3600, 'seconds')添加值,然后从 y 轴值或工具提示项中,您必须参考

callback: value => {
    date = moment.utc(value);
    if(date.diff(moment.utc('1970-01-01 23:59:59'), 'minutes') === 0) 
    {
        return null;
    };
    date.format('HH:mm:ss');
}

label: (item, data) => data.datasets[item.datasetIndex].label +" "+ 
moment.utc(data.datasets[item.datasetIndex].data[item.index]).format("HH:mm:ss")

https://lopeys.com/ironman/IMAUS_Charts_StackedTimes.htm

https://lopeys.com/ironman/IMAUS_Charts_StackedTimes.htm

回答by Jason Allshorn

My suggestion would be to add the moment.jslibrary to your project and format your dates using moment. Also I'm not sure about using the "t" and "y" here. I'd add the time as labels and matched that with the x data:

我的建议是将moment.js库添加到您的项目中并使用 moment 格式化您的日期。另外我不确定在这里使用“t”和“y”。我将时间添加为标签并将其与 x 数据匹配:

var data = {
  labels: [moment().format("YYYY-MM-DD"), moment().format("YYYY-MM-DD"), moment().format("YYYY-MM-DD")],
  datasets: [
    {
        data: [12,21,32],
    }
  ]
};

var myBarChart = Chart.Line(canvas,{
data:data,
});

There is a fiddle example here.

这里有一个小提琴示例