ChartsJS bar chart with HH:MM:SS format - javascript

I have a chartsJS as type: 'bar'. This works fine with data sets of numbers or string. How can I create a data set which consist of time format HH:MM:SS. My Chart so far looks like this:
let hours = ["40", "20", "15", "10"];
let frameworks = ['Week1', 'Week2', 'Week3'];
let myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: frameworks,
datasets: [{
data: hours,
}],
},
});
I want the array "hours" to consist of
let hours = ["01:00:00", "02:00:00", "03:00:00", "04:00:00"];
How can I format this? Been looking around and not been able to come up with a soluiton just yet.

I think you can do it with moment library.
It's the best library for working with time and dates.
You can find here documentation: https://momentjs.com/

Related

Sort JSON by names and not values

I'm running a query in java to get the quantity of calls in a time interval, the result of this query is:
Date(dd/mm/yyyy) | calls
_____________________|___________
17/05/18 | 30
16/05/18 | 36
10/05/18 | 14
27/04/18 | 12
26/04/18 | 90
But when I plot the result using chart js, data is displayed in the order as belows
Date(dd/mm/yyyy) | calls
_____________________|___________
10/05/18 | 14
26/04/18 | 90
27/04/18 | 12
16/05/18 | 36
17/05/18 | 30
¿How do I sort this JSON by date using javascript?
{2018-05-10: "14", 2018-04-26: "90", 2018-04-27: "12", 2018-05-16: "36", 2018-05-17: "30"}
First of all, your JSON is not valid. Those property names (the dates) must be quoted as strings for it to be valid.
Now, the best way to approach this is to actually change the JSON you're producing to an array:
data = [
{ "date": "2018-05-10", "hits": "14" },
{ "date": "2018-04-26", "hits": "90" },
// etc
];
If you produce this on the server, which should be easy to change, then processing it in the client should be a lot easier. In fact, if you can format your dates on the server as YYYY-MM-DD then, given the above, Chart.js should automatically understand it as a date and you can simply map it to the x axis with something like...
let data = ... // The array above
let chartData = data.map(function(p) {
return { x: p.date, y: p.hits };
});
var chart = new Chart(ctx, {
type: '...',
data: chartData,
// etc
});
If for whatever reason you cannot change the format of the JSON produced (but, of course, you still quote the dates to make the JSON valid), then you could try something like this:
let data = ... // Your JSON corrected to be valid
let chartData = Object.keys(data).map(function(k) {
let date = k.split('/').reverse().join('-');
return { x: date, y: data[k] };
});
var chart = new Chart({
type: '...',
data: chartData,
// etc
});

Programmatically highlighting DyGraph time series

I’m putting together an web-app that plots time series of weather data for the current year and the past 10 years on one dygraph. I want the time series for the current year (2015 at this time) to be highlighted relative to the past years, so I’m trying to increase the strokewidth for the current year from a default of 2 to 5. My problem is that I’m having trouble getting this to work programatically. The daily data for each year is in native array format, so the time series are identified by the contents of the array Yr0Labels:
["Date", "2005", "2006", "2007", "2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015"]
Next January 1 the Yr0Labels will programmatically change to:
["Date", "2006", "2007", "2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015",”2016”]
In the dygraph options parameter I set default strokeWidth to 2 and the strokeWidth for 2015 to 5. Because I want the current calendar year data to be highlighted properly after Jan. 1 , I’ve tried identifying the series to be highlighted by the contents of yr0Labels[11],
{
……
strokeWidth: 2,
labels: yr0Labels,
series: { yr0Labels[11] : { strokeWidth: 5} },
……..
}
This produced a syntax error - SyntaxError: missing : after property id
Suspecting that dygraph didn’t want to see array syntax in the series identifier, I tried to identify the series via a string variable “cyear”,
cyear = yr0Labels[11];
{…strokeWidth: 2,
labels: yr0Labels,
series: { cyear : { strokeWidth: 5} },
…….}
This didn’t produce an error, but also didn’t highlight the series.
The only way I’ve been able to make this work is to directly enter the current year value as the series identifier,
{…strokeWidth: 2,
labels: yr0Labels,
series : { ‘2015’ : { strokeWidth: 5} },
…….}
This worked, but I’d have to edit the dygraph option parameter every Jan. 1 to make data for the current calendar year plot properly.
How I can make this highlighting work programmatically?
The issue is with how you're using keys in JavaScript object literals.
This:
{ foo: 'bar' }
is the same as:
{ 'foo': 'bar' }
even if there's a variable in scope called foo. To achieve the result you want, you need to do fill out your objects using something like:
var foo = 'blah';
var o = {};
o[foo] = 'bar';

Highcharts proper usage of datetime?

My current setup is somewhat static with xaxis categories and tickinterval(cant even see the graph without tickinterval).
If you change screen resolution it looks somewhat bad and I would like to have the x-axis to be dynamic.
What I've gathered you should use data like this http://www.highcharts.com/samples/data/usdeur.js and xAxis like below?
xAxis: { type: 'datetime' }
But that example only uses YYMMDD, I also use hh:mm:ss.
Currently looks like this: i.imgur.com/v649otj.png
xAxis: {
categories: getjson('Date'),
tickInterval: 20
},
series: [
{name:'Cars', data: getjson('Values')},
]
Data:
getjson('Date') equals:
Array [ "2014-11-09 02:36:00", "2014-11-07 07:35:00", "2014-11-08 20:29:00", "2014-11-08 20:30:00", "2014-11-10 11:06:00", "2014-11-08 08:12:00", "2014-11-08 20:31:00", "2014-11-08 20:23:00", "2014-11-08 20:24:00", "2014-11-08 20:25:00", 190 till… ]
getjson('Values') equals:
Array [ 13, 209, 209, 19, 0, 209, 15, 13, 13, 19, 190 till… ]
So how do I make use of this data and the datetime configuration.
Somehow push the 'Date'-data into same array as 'values' and convert it into right date format?
Edit: Current work: http://jsfiddle.net/tws8x0pd/4/
Datetime configuration uses UTC numbers not YYMMDD! You should pass your datetime data with Date.UTC(year,month,day,hour,minute,second) in Series data with the format:
series: [
{name:'...', data: [ [ Date.UTC(year,month,day,hour,minute,second), value ],
[ Date.UTC(year,month,day,hour,minute,second), value ],
...
]
}
]
so you should get the year,month,... out of your json date and put it with the corresponding value in json values. Each in one array, not apart in separate arrays.
The time require to be as timestamp (time in miliseconds) not strnig as you have. So you need to prepare correct data by Date.parse() / Date.UTC()

Converting JS array UNIX date integers into JS Date objects

Is there a way to convert UNIX epoch integers (1402079444, etc) in an array into JavaScript Date objects (Date.UTC(2014, 9, 14), etc) using jQuery?
I'm trying to pass a large JSON array generated by PHP to Highmaps.JS, which almost works great however Highmaps expects a Date object and Date objects aren't valid JSON, so I can't generate them with PHP.
jsFiddle of my current setup here: http://jsfiddle.net/dwgLtscm/2/
(The x-axis isn't displaying dates properly because the data isn't in the proper date format).
[{
"name": "Dissolved Oxygen",
"data": [
[1402079444,9]
]
},
{
"name": "Temperature (Water)",
"data": [
[1401291099,9],
[1401862547,12]
]
},
{
"name": "Temperature (Air)",
"data": [
[1401291099,13],
[1401862547,19]
]
},
]
Given the Json object above, I'd try:
array.forEach(function (val) {
val.data = val.data.map(function (datum) {
return [ new Date(datum[0] * 1000), datum[1] ];
}
}
Unless I'm reading it wrong (I'm assuming data[0] is the UTC value).
(Edited based on feedback below, thanks all!)

Plot the json array using jquery flot

var data =[ { label: "Foo", data: [ ["2012-09-01", 1], ["2012-10-01", -14], ["2012-11-01", 5] ] },
{ label: "Bar", data: [ ["2012-09-01", 13], ["2012-10-01", 11], ["2012-11-01", -7] ] }
];
var options = {
series: {
lines: { show: true },
points: { show: true }
}
};
<div id="placeholder"></div>
<script>
$.plot($('#placeholder'), data, options);
</script>
I am confused why the graph is not getting plotted with the data. Ignore my novice knowledge on flot. Can anyone give me an idea how i should be able to do it.
Are you sure flot can handle values formatted as strings? You should probably convert the strings to real dates or milliseconds...
You can use the moment.js library:
var data =[ { label: "Foo", data: [ [moment("2012-09-01","YYYY-MM-DD").toDate(), 1], ...
Flot does not automatically parse dates. If you want those to be used as-is then you should include the categories plugin. If you actually want to treat them as dates then you should convert them to dates as Nikos suggested and then take a look at the time plugin.

Categories