[英]Chart.js - creating time series freqency chart with JSON data
so recently I've been working on a web app that collects data from requests and I am trying to output the data into a graph based on frequency per hour/month etc. 所以最近我一直在开发一个从请求中收集数据的Web应用程序,我试图根据每小时/每月的频率等将数据输出到图表中。
So, I'm using Chart.js and have JSON data of dates and I'm trying to make a chart that shows the frequency of requests per hour, etc. 因此,我正在使用Chart.js并具有日期的JSON数据,并且试图制作一个显示每小时请求频率等的图表。
My data is just each request has a time stamp, so all I have is a bunch of time stamps in 2018-01-03 15:15:04
format. 我的数据只是每个请求都有一个时间戳,所以我所拥有的只是一堆
2018-01-03 15:15:04
格式的时间戳。 for example: 例如:
{'2018-01-03 15:15:04', '2018-01-04 06:32:45', '2018-01-04 23:32:45', '2018-02-23 01:24:32'}
except, I have hundreds of them. 除了,我有数百个。 Just frequency per hour, month, etc is what I want.
我想要的只是每小时,每月等的频率。
Can anyone point me in the right direction? 谁能指出我正确的方向? My two thoughts were this:
我的两个想法是:
thanks a ton, everyone! 谢谢大家!
Here's an example of what I would like: Chart example 这是我想要的示例 : 图表示例
Also, http://www.chartjs.org/samples/latest/scales/time/financial.html 另外, http://www.chartjs.org/samples/latest/scales/time/financial.html
Going with #1 on your list is your best bet. 最好的选择是排在第一位。 I wrote an example of how you can achieve it pretty easily.
我写了一个示例,说明如何轻松实现它。
First find the frequency (I did it by month/year) and add it to a Map . 首先找到频率(我按月/年进行),然后将其添加到Map中 。 I used a map because the
.keys()
and .values()
functions for a Map are returned in insertion order. 我之所以使用地图,是因为
.keys()
和.values()
函数是按插入顺序返回的。 A regular object cannot guarantee order. 常规对象不能保证顺序。
Then, Chart.js can display those values pretty easily using spread syntax to turn the .keys()
and .values()
iterators into arrays. 然后,Chart.js可以使用扩展语法轻松地显示这些值,以将
.keys()
和.values()
迭代器转换为数组。
var a = ['2018-01-03 15:15:04', '2018-01-04 06:32:45', '2018-01-04 23:32:45', '2018-02-23 01:24:32', '2018-02-23 04:33:12', '2018-03-23 05:33:12', '2018-03-22 08:33:12', '2018-04-27 01:33:12']; var freqMap = new Map(); a.forEach(function(time) { var date = new Date(time); var monthName = date.toLocaleString("en-us", { month: "short" }); var key = monthName + "-" + date.getFullYear(); var count = freqMap.get(key) || 0; freqMap.set(key, ++count); }); var ctx = document.getElementById("myChart").getContext('2d'); var myLineChart = new Chart(ctx, { type: 'line', data: { labels: [...freqMap.keys()], datasets: [{ label: 'Requests per month', data: [...freqMap.values()] }], }, options: { elements: { line: { tension: 0 } }, scales: { yAxes: [{ ticks: { beginAtZero: true, stepSize: 1 } }] } } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js"></script> <canvas id="myChart" width="400" height="400"></canvas>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.