ECharts / JS - Format Time Int to H:M:S within Tooltip - javascript

I am trying to change a time int, such as 010511 into a human readable format of 01:05:11 for both the tooltip, and YAxis of Echarts.
Note that this isn't a timestamp, and is a stopwatch-type piece of data, always starting from 00:00:00 and going up.
Below is the current state of the EChart.
<!-- Echart JS CC -->
<script>
var chart = document.getElementById('cc_chart');
var myChart = echarts.init(chart);
var option = {
title: { text: '' },
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'cross',
label: {
backgroundColor: '#6a7985'
}
}
},
textStyle: {
color: '#fff'
},
grid: {
left: '0',
right: '4%',
bottom: '27%',
top: '4%',
containLabel: true
},
dataZoom: [
{
type: 'inside',
start: 0,
end: 100
},
{
show: true,
type: 'slider',
y: '75%',
start: 0,
end: 100
}
],
legend: {
data: ["Bobby", "Freddy"],
textStyle: {
},
textStyle: {
color: '#fff'
},
bottom: 0,
},
xAxis: {
boundaryGap : false,
data: ["19/03/18","20/03/18","21/03/18","22/03/18","23/03/18","26/03/18","27/03/18","29/03/18","03/04/18"]
},
yAxis: {
boundaryGap : false
},
series: [
{
name: 'Bobby',
type: 'line',
areaStyle: {normal: {}},
symbol: 'circle',
symbolSize: 8,
data: ["011441","011614","011614","003815","001915","003610","000432","000458","005801"]
},
{
name: 'Freddy',
type: 'line',
areaStyle: {normal: {}},
symbol: 'circle',
symbolSize: 8,
data: ["001725","001725","001725","003239","010239","002531","005208","004547","002441"]
},
]
};
myChart.setOption(option);
</script>
How do I change the int value into a more human readable format, within ECharts?

Solved it with the below!
tooltip: {
trigger: 'axis',
formatter: function(params) {
params.sort(function(a,b) { // Sort params by value size first
return parseInt(b.value) - parseInt(a.value)
});
output = '<b>' + params[0].name + '</b><br/>'
for (i = 0; i < params.length; i++) {
output += params[i].marker + params[i].seriesName + ': ' + params[i].value.match(/\d\d/g).join(':'); // : every 2nth
if (i != params.length - 1) { // Append a <br/> tag if not last in loop
output += '<br/>'
}
}
return output
}
}
First we sort the params array with a .sort() function, then we create an output containing the date of the first result as the title (The date will be on every other record, so grabbing it from the first result is fine), then we iterate over the length of the array, appending values we want to the output (formatted using kshetline's answer!), and checking if it's the last result in the array so we can add break tags.

If the time value is reliably six characters like in your examples, call the time value t, and formatting would look like this:
t.substr(0, 2) + ':' + t.substr(2, 2) + ':' + t.substr(4, 2)
Or this, a bit more elegant:
t.match(/\d\d/g).join(':')

params.value[0] contains date in yyyy-mm-dd format
tooltip: {
trigger: 'axis',
formatter: function(params) {
params = params[0];
var chartdate = echarts.format.formatTime('dd-MM-yyyy', params.value[0]);
var val = '<li style="list-style:none">' + params.marker +
params.seriesName + ' ' + params.value[1] + '</li>';
return chartdate + val;
}
},

Based on #pujitha-pinky answer you can adapt it to a multiple series chart like this (example with formating the date to a fr-FR local):
tooltip = {
trigger: "axis",
formatter: function (params) {
var chartdate = (new Date(params[0].value[0])).toLocaleDateString("fr-FR", {
year: "numeric",
month: "2-digit",
day: "2-digit",
});
var vals = params.reduce((prev, curr) => prev + '<li style="list-style:none">' + curr.marker + curr.seriesName + " " + curr.value[1] + "</li>", "");
return chartdate + vals;
},
};

Related

Have an issue with JavaScript, AJAX code displaying data

I need some tips from you out there to come over a good solution on my problem with JavaScript, AJAX and JSON data. I want to fill a generic set with barcharts (I am using HighCharts) on my web page. The data is in JSON format which from the start I only used date and value as pair data set. The solution works fine of I had only one bar chart it, but I have a lot of charts on my page and I need to show all of them (up to twelve).
Now I want to adjust for displaying more than one graph. In the code below the DataMacro array works fine with the chart. It also has a hard coded ID matching a . Now I have a series of in the page like id=barchart11, id=barchar21, and so on. In the dataset I have made a tag called PanelCodeUI that I am going to use looping through the dataset. The problem is how to do that. The each-loop will now fill in all date,value for all vessels.
And further it I need to restructure the function which is displaying the barchart. The best thing would be to call a function with a data array and panelCodeUI id just replacing the name of the barchart and set in the datamacro as is. But I don’t know how to do this. The data is mixed between all vessels and I need to collect all data before sending to a function. So is the problem with AJAX and JavaScript with is asynchron. I need to ensure that it behaves correctly and fast.
Maybe I need to change my dataset, or I need to do this in several step like finding all vessel IDs then do another AJAX call to get date,value pair from a vessel and then displaying. I hope there is a way to do this with this data set and hope somebody can help me on this
Here is a bit of the JSON data set:
[
{"__type":"Demo.Entities.OilProductionLast5DaysEntity","Date":1465084800000,"Value":844,"VesselId":1,"SectorId":2,"PanelCodeUI":"21","VesselCodeUI":"21","VesselSorting":1},
{"__type":"Demo.Entities.OilProductionLast5DaysEntity","Date":1465084800000,"Value":8720,"VesselId":4,"SectorId":1,"PanelCodeUI":"11","VesselCodeUI":"12","VesselSorting":2},
{"__type":"Demo.Entities.OilProductionLast5DaysEntity","Date":1465084800000,"Value":948,"VesselId":5,"SectorId":1,"PanelCodeUI":"11","VesselCodeUI":"11","VesselSorting":1},
{"__type":"Demo.Entities.OilProductionLast5DaysEntity","Date":1465084800000,"Value":0,"VesselId":6,"SectorId":3,"PanelCodeUI":"31","VesselCodeUI":"31","VesselSorting":1},
{"__type":"Demo.Entities.OilProductionLast5DaysEntity","Date":1465171200000,"Value":2067,"VesselId":1,"SectorId":2,"PanelCodeUI":"21","VesselCodeUI":"21","VesselSorting":1}
]
And here is the JavaScript code so far:
$(function () {
var datamacro = [];
$.ajax({
type: "POST",
url: '../Services/HighChartService.asmx/GetOilProductionLast5DaysByActiveVessels',
data: '',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (seriedata) {
console.log(JSON.stringify(seriedata.d));
var productions = seriedata.d;
$.each(productions, function (index, productions) {
var yval = productions.Value;
var xval = productions.Date;
var x = [xval, yval];
datamacro.push(x);
//alert("productions Name: " + productions.Date + "\nID: " + productions.Value);
});
$(function () {
//var bchart = '#barchart' + vesselindex.toString();
// want this to be looped with generic names like #barchart11, #barchart21, #barchart31 and so on
$('#barchart11').highcharts({
chart: {
type: 'column'
},
title: {
text: 'LAST FIVE DAYS'
},
subtitle: {
text: ''
},
xAxis: {
type: "datetime",
tickInterval: 24 * 3600 * 1000,
labels: {
rotation: -45,
align: 'right'
},
dateTimeLabelFormats: { // don't display the dummy year
day: '%e. %b',
},
//crosshair: true
},
credits: {
enabled: false
},
yAxis: {
labels: {
enabled: false
},
title: {
text: null
}
},
tooltip: {
formatter: function () {
return Highcharts.dateFormat('%d/%m/%Y', new Date(this.x)) + '<br/>' + ' in barrels: ' + this.y;
}
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}, series: {
pointRange: 24 * 3600 * 1000, // one day
pointInterval: 3600 * 1000
}
},
series: [{
//name: '',
showInLegend: false,
data: datamacro,
dataLabels: {
enabled: true,
rotation: -90,
color: '#FFFFFF',
align: 'right',
format: '{point.y:.1f}', // one decimal
y: 10, // 10 pixels down from the top
style: {
fontSize: '13px',
fontFamily: 'Verdana, sans-serif'
}
}
}]
});
});
},
error: function (r) {
alert(r.responseText);
},
failure: function (r) {
alert(r.responseText);
}
});
});
If i understand correctly, you would like to draw a chart for each different panelCodeUI ?
If that's the case, change your code after AJAX success with that :
var productions = seriedata.d;
var listPanelCodeUI = productions.map(function(p){return p.PanelCodeUI}).filter(function(item, pos, self) {
return self.indexOf(item) == pos;
});
//listPanelCodeUI : [21,11,31]
listPanelCodeUI.sort();
listPanelCodeUI.forEach(function(e){
datamacro = [];
//Create a div for each panelCodeUI
$("body").append("<div id='barchart" + e + "'></div>");
var divId = "#barchart"+e;
//Filter productions for specific panelCodeUI
var data = productions.filter(function(p){return p.panelCodeUI === e});
data.forEach(function(d){
var yval = d.Value;
var xval = d.Date;
var x = [xval, yval];
datamacro.push(x);
});
$(function () {
$(divId).highcharts({
...
})
})
}
That's what you need to parse your data:
charts = [];
$.each(productions.map(function(el) {
return el.PanelCodeUI;
}).filter(function(el, index, arr) {
return arr.indexOf(el) === index;
}), function(index,PanelCodeUI) {
var serie = productions.filter(function(el) {
return el.PanelCodeUI === PanelCodeUI;
});
$.each(serie, function(index, production) {
datamacro.push([production.Value, production.Date]);
});
drawChart('#barchart' + PanelCodeUI, 'LAST FIVE DAYS', datamacro);
});
Also i made this helper function to create the charts:
function drawChart(containerID, chartTitle, data) {
charts.push(new Highchart.Chart({
chart: {
type: 'column',
renderTo: containerID
},
title: {
text: chartTitle
},
subtitle: {
text: ''
},
xAxis: {
type: "datetime",
tickInterval: 24 * 3600 * 1000,
labels: {
rotation: -45,
align: 'right'
},
dateTimeLabelFormats: { // don't display the dummy year
day: '%e. %b',
},
//crosshair: true
},
credits: {
enabled: false
},
yAxis: {
labels: {
enabled: false
},
title: {
text: null
}
},
tooltip: {
formatter: function() {
return Highcharts.dateFormat('%d/%m/%Y', new Date(this.x)) + '<br/>' + ' in barrels: ' + this.y;
}
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
},
series: {
pointRange: 24 * 3600 * 1000, // one day
pointInterval: 3600 * 1000
}
},
series: [{
//name: '',
showInLegend: false,
data: data,
dataLabels: {
enabled: true,
rotation: -90,
color: '#FFFFFF',
align: 'right',
format: '{point.y:.1f}', // one decimal
y: 10, // 10 pixels down from the top
style: {
fontSize: '13px',
fontFamily: 'Verdana, sans-serif'
}
}
}]
}));
}

Updating highcharts live data not working

I have some UV Sensors (currently running on Thingspeak) - but I need to have multiple series on the same chart, so I made a sample .php page on my website.
I have the basic chart working nicely, but I have not been able to get it to do live updates - my coding skills are very lacking & I would appreciate any help I can get!
The sample chart is here: http://www.sesupply.co.nz/test.php
I have the code on JSFiddle here: https://jsfiddle.net/SESupply/9xn65qrL/9/
// variables for the first series
var series_1_channel_id = 43330;
var series_1_field_number = 4;
var series_1_read_api_key = '7ZPHNX2SXPM0CA1K';
var series_1_results = 480;
var series_1_color = '#d62020';
var series_1_name = 'Zims Sensor';
// variables for the second series
var series_2_channel_id = 45473;
var series_2_field_number = 2;
var series_2_read_api_key = 'N12T3CWQB5IWJAU9';
var series_2_results = 480;
var series_2_color = '#00aaff';
var series_2_name = 'UVM30A';
// chart title
var chart_title = 'UV Sensors Zim / UVM30A';
// y axis title
var y_axis_title = 'UV Index';
// user's timezone offset
var my_offset = new Date().getTimezoneOffset();
// chart variable
var my_chart;
// when the document is ready
$(document).on('ready', function () {
// add a blank chart
addChart();
// add the first series
addSeries(series_1_channel_id, series_1_field_number, series_1_read_api_key, series_1_results, series_1_color, series_1_name);
// add the second series
addSeries(series_2_channel_id, series_2_field_number, series_2_read_api_key, series_2_results, series_2_color, series_2_name);
});
// add the base chart
function addChart() {
// variable for the local date in milliseconds
var localDate;
// specify the chart options
var chartOptions = {
chart: {
renderTo: 'chart-container',
defaultSeriesType: 'spline',
zoomType: 'x', // added here
panning: true,
panKey: 'shift',
backgroundColor: '#ffffff',
events: {
load: addSeries
}
},
title: {
text: chart_title
},
subtitle: {
text: 'Click and drag to zoom in. Hold down shift key to pan.'
},
plotOptions: {
series: {
marker: {
radius: 2
},
animation: true,
step: false,
borderWidth: 0,
turboThreshold: 0
}
},
scrollbar: {
enabled: true
// barBackgroundColor: 'gray',
// barBorderRadius: 7,
// barBorderWidth: 0,
// buttonBackgroundColor: 'gray',
// buttonBorderWidth: 0,
// buttonArrowColor: 'yellow',
// buttonBorderRadius: 7,
// rifleColor: 'yellow',
// trackBackgroundColor: 'white',
// trackBorderWidth: 1,
// trackBorderColor: 'silver',
// trackBorderRadius: 7
},
tooltip: {
// reformat the tooltips so that local times are displayed
formatter: function () {
var d = new Date(this.x + (my_offset * 60000));
var n = (this.point.name === undefined) ? '' : '<br>' + this.point.name;
return this.series.name + ':<b>' + this.y + '</b>' + n + '<br>' + d.toDateString() + '<br>' + d.toTimeString().replace(/\(.*\)/, "");
}
},
xAxis: {
type: 'datetime',
title: {
text: 'Date'
}
},
rangeSelector: {
enabled: true,
buttons: [{
type: 'minute',
count: 60,
text: 'Hour'
}, {
type: 'day',
count: 1,
text: 'Day'
}, {
type: 'week',
count: 1,
text: 'Week'
}, {
type: 'all',
text: 'All'
}]
},
yAxis: {
title: {
text: y_axis_title
}
},
exporting: {
enabled: true
},
legend: {
enabled: true
},
credits: {
text: 'ThingSpeak.com',
href: 'https://thingspeak.com/',
style: {
color: '#D62020'
}
}
};
// draw the chart
my_chart = new Highcharts.Chart(chartOptions);
}
// add a series to the chart
function addSeries(channel_id, field_number, api_key, results, color, name) {
var field_name = 'field' + field_number;
// get the data with a webservice call
$.getJSON('https://api.thingspeak.com/channels/' + channel_id + '/fields/' + field_number + '.json?offset=0&round=2&results=' + results + '&api_key=' + api_key, function (data) {
// blank array for holding chart data
var chart_data = [];
// iterate through each feed
$.each(data.feeds, function () {
var point = new Highcharts.Point();
// set the proper values
var value = this[field_name];
point.x = getChartDate(this.created_at);
point.y = parseFloat(value);
// add location if possible
if (this.location) {
point.name = this.location;
}
// if a numerical value exists add it
if (!isNaN(parseInt(value))) {
chart_data.push(point);
}
});
// add the chart data
my_chart.addSeries({
data: chart_data,
name: name,
color: color
});
});
setTimeout(addSeries, 1000);
}
cache: false;
// converts date format from JSON
function getChartDate(d) {
// offset in minutes is converted to milliseconds and subtracted so that chart's x-axis is correct
return Date.parse(d) - (my_offset * 60000);
}
I have tried following the livedata example but seem to be failing miserably. The sensors update about every 60 seconds (only during the day - as there is no UV at night, I put the sensors into "sleep" mode to save battery power)

Displaying time based logs in in HighCharts

I need to display time value of some logs which I fetch from a device,on X-axis of a column graph. The column graph has constant values for Y-axis, basically I want the logs to be shown as sticks as the logs are fetched.
The logs have the following date,time format : 2015-05-07T06:08:54.430062Z
I understand this is the ISO format, so I convert "06:08:54.430062" to milliseconds using
var myDate = new Date(dt);
var result = myDate.getTime();
The result obtained is like this 1430978934438. It so happens that when I convert I get similar values for other logs as well, even if they have a different time instant.
So suppose I have 10 logs, the graph only shows 4 of them. I use
var value=10;// this is a fixed constant value, since I want the log sticks to be of same height.
series.addPoint([result , value], false, false);
How can I see all the logs as sticks corresponding to each log entry ?
If you need more information, let me know. I am fairly new to HighCharts and JS, so any help in the right direction would be really helpful.
Thanks
Added code below
for (var i = 0; i < nSeries; i++) {
dt=jsonData[i].isodate;
var myDate = new Date(dt);
var result = myDate.getTime();
var series = mychart.series[0];
series.addPoint([result, value], false, false);
}
mychart.redraw();
instance.create = function(Highcharts, container) {
Highcharts.setOptions({
global: {
useUTC: false
}
});
var self = this;
mychart = new Highcharts.Chart({
chart: {
renderTo: container,
defaultSeriesType: 'column',
plotBorderWidth: 1,
showAxes: true,
animation: Highcharts.svg
},
title: {
text: 'Logs'
},
xAxis: {
type: 'datetime',
events: {
setExtremes: function (e) {
console.log('e.min: ' + Highcharts.dateFormat(null, e.min) +
' | e.max: ' + Highcharts.dateFormat(null, e.max) + ' | e.trigger: ' + e.trigger);
if (e.trigger) {
self.autoScroll = false;
}
}
}
},
yAxis: {
title: {
text: ''
}
},
tooltip: {
formatter: function () {
console.log(this);
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.dateFormat('%H:%M:%S.%L', this.x) + '<br/>'+this.key;
}
},
legend: {
enabled: true
},
exporting: {
enabled: true
},
plotOptions: {
column: {
stacking: null
}
},
scrollbar: {
enabled: true
},
series: [{
name: 'Logs',
data: [],
stack: 'LogStack'
}]
});
};

Highcharts not Drawing point on setInterval

I have data being put on an api every 30 seconds on a backend. On the frontend I am using highcharts to visualize the data and a setInterval setup to retrieve the new data every 30 seconds. My problem is that on that setInterval, the line graph disappears or does not draw to the next new dot. Does anyone now why this is?
fiddle: http://jsfiddle.net/b8tf281n/3/
code:
chart1 = {
yAxisMin: 40,
yAxisMax: 100
};
// empty objects for our data and to create chart
seriesData = [];
BPM = [];
time1 = [];
// console.log(chart1.data.series);
$(function () {
$(document).ready(function () {
Highcharts.setOptions({
global: {
useUTC: false
}
});
var url = 'http://msbandhealth.azurewebsites.net/odata/PulsesAPI/';
$.ajax({
url: url,
dataType: 'json',
context: seriesData,
success: function (data) {
// structure our data
for (var i = 0; i < data.value.length; i++) {
bpm = data.value[i].BPM;
time = data.value[i].Time;
BPM.push({
x: moment(time),
y: bpm
});
// console.log(BPM);
time1.push(time);
}
console.log((new Date).getTime());
console.log(moment(time, "DD.MM.YYYY hh:mm:ss"));
console.log(BPM);
console.log(BPM[BPM.length - 1]);
// console.log(seriesData);
// set our data series and create new chart
chart1.data.series[0].data = BPM;
chart = new Highcharts.Chart(chart1.data);
$('#container').css({
height: '400px'
});
// console.log(sortedBPM);
// console.log(time1);
}
});
// give highcharts something to render to
var container = document.getElementById("container");
chart1.data = {
chart: {
renderTo: container,
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: function () {
setInterval(function () {
// find last data points
var test = BPM[BPM.length - 1];
var x = (new Date).getTime(),
y = test.y;
console.log(x);
shift = chart.series[0].data.length < 30;
chart.series[0].addPoint([x, y], true, true);
},
30000);
}
}
},
title: {
text: 'Microsoft Band: Real Time Pulse Analysis'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
dateTimeLabelFormats: {
},
},
yAxis: {
min: chart1.yAxisMin,
max: chart1.yAxisMax,
title: {
text: 'Heart Rate'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' + Highcharts.dateFormat('%H:%M:%S', this.x) + '<br/>' + Highcharts.numberFormat(this.y, 2);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Beats Per Minute',
data: []
}]
};
});
});
Your test.y is the problem. It returns undefined after one interval. Somehow BPM is changing in it's structure - changing each object from {x,y} to [0,1] - therefore I used:
y = (test.y !== undefined)? test.y : test[1];
to either get the previous structure or the new. I also set the interval to 3 seconds for you to see the difference easier. Here's the DEMO.

Highcharts tooltip not working

I cannot figure out how to get the 'to' and 'from' dates from my data into the tooltips. Tried various methods I found around SO. Anyone got any tips? I normally load data from CSV. Right now the data is hard-coded in the code.
var options = {
chart: {
zoomType: 'y',
borderWidth: '0',
borderRadius: '15',
renderTo: 'container',
inverted: true,
backgroundColor: {
linearGradient: [0, 0, 500, 500],
stops: [
[0, 'rgb(44, 44, 58)'],
[1, 'rgb(62, 62, 62)']
]
},
plotBackgroundColor: 'rgba(255, 255, 255, .9)'
},
tooltip: {
formatter: function () {
var point = this.point;
return '<b>' + point.category +
'</b><br/>' + Highcharts.dateFormat('%b %e, %Y', this.y) +
' - ' + Highcharts.dateFormat('%b %e, %Y', this.series[0]);
}
},
legend: {
enabled: false
},
title: {
text: 'EVMS Calendar'
},
xAxis: {
categories: []
},
plotOptions: {
series: {
grouping: false
}
},
yAxis: {
type: 'datetime',
minRange: '604800000',
startOnTick: false,
endOnTick: false,
title: {
text: ''
}
},
series: []
},
categories = [];;
//// This is the data processing section \\\\
// Hard Coded Data
var data ="valid data";
// Split the lines
var lines = data.split('\n');
// Iterate over the lines and add categories or series
// Split the data by comma
// Get the number of items in the object (iLen)
// Series start
// Series type is columnrange
// Servies name is item 0 of the line (employees name)
$.each(lines, function (lineNo, line) {
var items = line.split(','),
iLen = items.length,
series = {
type: 'columnrange',
data: [],
name: items[0]
};
// Start categories
// for each items (0) get the row data (dates) and push to categories(line number, from and to)
categories.push(items[0]);
for (var i = 1; i < iLen; i += 2) {
var from = (new Date(items[i])).getTime(),
to = (new Date(items[i + 1])).getTime();
if (!isNaN(from) && !isNaN(to)) {
series.data.push([lineNo, from, to]);
}
};
options.series.push(series);
});
options.xAxis.categories = categories;
// Create the chart
var chart = new Highcharts.Chart(options);
ah, my bad. Its this.point.high / low. I found out by looking through the elements in chrome

Categories