Reputation: 107
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.
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.
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. 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
Upvotes: 0
Views: 3376
Reputation: 5486
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. I used a map because the .keys()
and .values()
functions for a Map are returned in insertion order. 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.
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>
Upvotes: 2