Date not showing correct in High Chart x-xis - php

My JSON:
[{"date":"2016,07,01","coached":"0.00000000000000","non_coached":"1.07262272089762","delta":-1.0726227208976},{"date":"2016,06,24","coached":"0.00000000000000","non_coached":"0.64400560224090","delta":-0.6440056022409},{"date":"2016,06,17","coached":"1.13666666666667","non_coached":"0.41228898426323","delta":0.72437768240344},{"date":"2016,06,10","coached":"0.68866666666667","non_coached":"0.46050000000000","delta":0.22816666666667},{"date":"2016,06,03","coached":"0.68666666666667","non_coached":"0.19209103840683","delta":0.49457562825984},{"date":"2016,05,27","coached":"-0.03933333333333","non_coached":"-0.04332859174964","delta":0.00399525841631},{"date":"2016,05,20","coached":"0.01214285714286","non_coached":"-0.07948965517241","delta":0.09163251231527},{"date":"2016,05,13","coached":"0.30733333333333","non_coached":"-0.10541436464088","delta":0.41274769797421},{"date":"2016,05,06","coached":"0.20937500000000","non_coached":"0.00750704225352","delta":0.20186795774648},{"date":"2016,04,29","coached":"0.00133333333333","non_coached":"-0.10642559109875","delta":0.10775892443208},{"date":"2016,04,22","coached":"-0.25600000000000","non_coached":"-0.06736248236953","delta":-0.18863751763047},{"date":"2016,04,15","coached":"0.31375000000000","non_coached":"-0.05191489361702","delta":0.36566489361702},{"date":"2016,04,08","coached":"-0.28800000000000","non_coached":"-0.00908682634731","delta":-0.27891317365269},{"date":"2016,04,01","coached":"0.14466666666667","non_coached":"-0.01988522238164","delta":0.16455188904831},{"date":"2016,03,25","coached":"0.20000000000000","non_coached":"0.05398581560284","delta":0.14601418439716},{"date":"2015,12,25","coached":"0.01344827586207","non_coached":"-0.06062585034014","delta":0.07407412620221},{"date":"2015,12,18","coached":"0.26806451612903","non_coached":"-0.00484311050477","delta":0.2729076266338},{"date":"2015,12,11","coached":"0.25352941176471","non_coached":"-0.01641483516484","delta":0.26994424692955},{"date":"2015,12,04","coached":"0.15000000000000","non_coached":"0.00259002770083","delta":0.14740997229917},{"date":"2015,11,27","coached":"0.18500000000000","non_coached":"0.06243626062323","delta":0.12256373937677},{"date":"2015,11,20","coached":"0.20500000000000","non_coached":"-0.06820584144645","delta":0.27320584144645},{"date":"2015,11,13","coached":"0.28800000000000","non_coached":"0.14813559322034","delta":0.13986440677966},{"date":"2015,11,06","coached":"0.05097560975610","non_coached":"0.02680397727273","delta":0.02417163248337},{"date":"2015,10,30","coached":"0.25279069767442","non_coached":"0.13122392211405","delta":0.12156677556037},{"date":"2015,10,23","coached":"0.06536585365854","non_coached":"0.12291605301915","delta":-0.05755019936061},{"date":"2015,10,16","coached":"0.03487804878049","non_coached":"0.30552833078101","delta":-0.27065028200052},{"date":"2015,10,09","coached":"0.06000000000000","non_coached":"0.17649499284692","delta":-0.11649499284692},{"date":"2015,10,02","coached":"0.18186046511628","non_coached":"0.30160173160173","delta":-0.11974126648545},{"date":"2015,09,25","coached":"-0.04195121951220","non_coached":"0.32907246376812","delta":-0.37102368328032},{"date":"2015,09,18","coached":"0.17447368421053","non_coached":"0.26081447963801","delta":-0.08634079542748},{"date":"2015,09,11","coached":"-0.04069767441860","non_coached":"0.39883058470765","delta":-0.43952825912625},{"date":"2015,09,04","coached":"0.13073170731707","non_coached":"0.29857580398162","delta":-0.16784409666455},{"date":"2015,08,28","coached":"0.39302325581395","non_coached":"0.30868827160494","delta":0.08433498420901},{"date":"2015,08,21","coached":"0.13843137254902","non_coached":"0.25431578947368","delta":-0.11588441692466},{"date":"2015,08,14","coached":"0.18000000000000","non_coached":"0.21200328407225","delta":-0.03200328407225},{"date":"2015,08,07","coached":"0.37620000000000","non_coached":"0.18070000000000","delta":0.1955},{"date":"2015,07,31","coached":"0.35239130434783","non_coached":"0.17344208809135","delta":0.17894921625648},{"date":"2015,07,24","coached":"0.01840909090909","non_coached":"0.24440514469453","delta":-0.22599605378544},{"date":"2015,07,17","coached":"0.16108695652174","non_coached":"0.26153225806452","delta":-0.10044530154278},{"date":"2015,07,10","coached":"0.16166666666667","non_coached":"0.31383471074380","delta":-0.15216804407713},{"date":"2015,07,03","coached":"0.11671875000000","non_coached":"0.21704361873990","delta":-0.1003248687399},{"date":"2015,06,26","coached":"0.30638888888889","non_coached":"0.17638668779715","delta":0.13000220109174},{"date":"2015,06,19","coached":"0.37225352112676","non_coached":"0.24194221508828","delta":0.13031130603848},{"date":"2015,06,12","coached":"0.25636363636364","non_coached":"0.21017214397496","delta":0.04619149238868},{"date":"2015,06,05","coached":"0.17027027027027","non_coached":"0.21259375000000","delta":-0.04232347972973},{"date":"2015,05,29","coached":"-0.36263888888889","non_coached":"0.05622291021672","delta":-0.41886179910561},{"date":"2015,05,22","coached":"0.18888888888889","non_coached":"0.18983076923077","delta":-0.00094188034188},{"date":"2015,05,15","coached":"-0.05687500000000","non_coached":"0.12545592705167","delta":-0.18233092705167},{"date":"2015,05,08","coached":"0.20102564102564","non_coached":"0.15625570776256","delta":0.04476993326308},{"date":"2015,05,01","coached":"0.07525000000000","non_coached":"0.12190193164933","delta":-0.04665193164933},{"date":"2015,04,24","coached":"0.29610389610390","non_coached":"0.13772519083969","delta":0.15837870526421},{"date":"2015,04,17","coached":"0.01613333333333","non_coached":"0.03368916797488","delta":-0.01755583464155},{"date":"2015,04,10","coached":"0.21420289855072","non_coached":"0.05916018662519","delta":0.15504271192553},{"date":"2015,04,03","coached":"-0.01797297297297","non_coached":"-0.05907435508346","delta":0.04110138211049},{"date":"2015,03,27","coached":"-0.00767123287671","non_coached":"0.06102201257862","delta":-0.06869324545533}]
Just want to show the first 13 weeks of data.
This is my code to process the JSON:
var series = [{name:'Coached',data:[]},{name:'Non Coached',data:[],stack: 'yes'},{name:'Opportunity',data:[],stack: 'yes'}],
year, month, day;
for(var i=0; i<13;i++){
var d = response[i].date.split(",");
year = d[0];
month = d[1];
day = d[2];
var coached = parseFloat(response[i].coached);
var non_coached = parseFloat (response[i].non_coached);
var delta = parseFloat (response[i].delta);
series[0].data.push([Date.UTC(year,month,day),coached]);
series[1].data.push([Date.UTC(year,month,day),non_coached]);
series[2].data.push([Date.UTC(year,month,day),delta]);
alert(Date.UTC(year,month,day));
}
console.log(series);
if(series.length){
stacked_chart_eCo_prod.userOptions.series = series;
var chart = new Highcharts.Chart(stacked_chart_eCo_prod.userOptions);
console.log(chart.series[0].data[0].options);
console.log(chart.series[1].data[0].options);
console.log(chart.series[2].data[0].options);
}
This is the PHP code:
stacked_chart_eCo_prod = new Highcharts.Chart({
colors: ['#003399','#910000','#55BF3B'],
chart: {
renderTo: 'stacked_chart_eCo_prod',
type: 'column'
},
title:{
text:''
},
yAxis: {
format: '{value:.2f}',
title: {
text: 'Job Uplift'
}
},
xAxis: {
type: 'datetime',
labels: {
format: '{value:%Y-%m-%d}',
align: 'right',
rotation: -30
}
},
plotOptions: {
column: {
stacking: 'normal'
// keys:['x','y','stack']
}
},
series: []
});
The date shown on the x-axis is wrong.
I have looked at this example but no use.
Any ideas what am I missing here?
Here is the issue. I think Date.UTC method is not working properly?

Related

Line Chart using Chart js with time data

I am creating a line chart using chartJs by passing date at X-Axis and time (mm:ss) at Y-Axis. I am not sure how to use chartJs with time values.I tried different solutions from stack but none works in my case.
Here is json file
{"label":["08-Aug-2019","11-Aug-2019","22-Aug-2019","25-Aug-2019"],"time":["1:08","1:44","2:27","1:02"],"chart_data":"{\"label\":[\"08-Aug-2019\",\"11-Aug-2019\",\"22-Aug-2019\",\"25-Aug-2019\"],\"time\":[\"1:08\",\"1:44\",\"2:27\",\"1:02\"]}"}
Here is what i am trying to code
<div id="time_chart"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.js"></script>
<script>
let sData = JSON.parse('<?php echo $chart_data; ?>');
let time_ctx = $("#time-chart");
//Line Chart
var time_data = {
labels: sData.label,
datasets: [
{
label: sData.label,
data: sData.time
}
]
};
//options line chart
var time_options = {
responsive: true,
title: {
display: false
},
legend: {
display: false
},
scales: {
yAxes: [{
type: 'time',
time: {
parser: 'm:s',
unit: 'minute',
unitStepSize: 2,
min: '0:0',
max: '30:00',
displayFormats: {
'seconds': 'm.s'
}
},
ticks: {
callback: function(value, index, values) {
//Ticks reverse does not work with time axes so we have to revert in this callback
if (values[values.length - index] != undefined) {
return moment(values[values.length - index].value).format('m.s');
}
}
}
}]
}
};
var chart2 = new Chart(time_ctx, {
type: "line",
data: time_data,
options: time_options
});
</script>
This is what I am getting with this code:
Although I didn't manage to use a time axis for both the x- and y-axes, I managed to create a workaround with a timed x-axis and a linear y-axis.
I parse your time and return the time in seconds (integer). I use this value to display your time and change the format back to mm:ss.
I hope this is what you wanted. I'm not sure you want the axes this way (because in your code you use the y-axis as type "time").
PS: My first post, please feel free to tell me what I can improve.
JSFiddle: https://jsfiddle.net/5837nmyo/
JSBin: https://jsbin.com/yadixolica/1/edit?html,js,output
let sData = {}
sData.label = ["08-Aug-2019","11-Aug-2019","22-Aug-2019","25-Aug-2019"]
sData.time = ["1:08","1:44","2:27","1:02"]
let chartData = {}
chartData.label = sData.label
chartData.time = parseTimeToSeconds(sData.time)
function parseTimeToSeconds(times){
let regex = /(\d*):(\d{2})/gm
let parsedTime = []
for (let x = 0; x < times.length; x++) {
let match = regex.exec(times)
parsedTime.push(parseInt(match[1])*60 + parseInt(match[2]))
}
return parsedTime
}
let time_ctx = document.getElementById('time_chart');
let time_data = {
labels: chartData.label,
datasets: [{
label: chartData.label,
data: chartData.time
}]
};
let time_options = {
responsive: true,
title: {
display: false
},
legend: {
display: false
},
tooltips: {
callbacks: {
label: function(tooltipItem, data){
let value = parseInt(tooltipItem.value)
if (value%60 < 10)
return Math.floor(value/60) + ":" + 0 + value%60
else
return Math.floor(value/60) + ":" + value%60
}
}
},
scales: {
xAxes: [{
type: 'time'
}],
yAxes: [{
ticks: {
min: 0,
max: 1800,
stepSize: 120,
callback: function(value, index, values) {
if (value%60 < 10)
return Math.floor(value/60) + ":" + 0 + value%60
else
return Math.floor(value/60) + ":" + value%60
}
}
}]
}
};
let chart2 = new Chart(time_ctx, {
type: "line",
data: time_data,
options: time_options
});

Flot Charts using SQL Server db with multiple y axis

This is my first post, apologies if I've asked a question a number of people have already done so. I don't see the answer I need in other posts.
I'm using Flot Charts and have a SQL Server db, I've got a php file that will connect to the db and return all the values within the sql in an array.
<?php
$server = "XXXX";
$database = "XXXX";
$user = "ReportsUser";
$pwd = "ReportsUser";
$cnn = odbc_connect("Driver={SQL Server Native Client 10.0};Server=$server;Database=$database;", $user, $pwd);
if(!$cnn)
{
echo "error in connecting";
}
$sql = odbc_exec($cnn, "
SELECT Months
,Referrals
,ProjectedVol
FROM mis.ReferralsBudgetvsActual
WHERE Months <= MONTH(GETDATE())
");
while($result = odbc_fetch_array($sql))
{
$allreferrals[] = array($result['Months'],$result['Referrals'],$result['ProjectedVol']);
}
echo json_encode(($allreferrals), JSON_NUMERIC_CHECK);
exit;
?>
This works well and produces the array as below
[[1,5981,7465],[2,5473,6962],[3,4974,7391],[4,5731,6985],[5,5891,7080],[6,5168,7136],[7,5551,7543],[8,4427,7242],[9,4617,7204],[10,4807,7642]]
Now, when it all comes together in the jquery file, this is where I end up getting stuck. I don't see where it pulls any other columns back apart from the first data column, how can this be done?
// document ready function
$(document).ready(function() {
var chartColours = ['#88bbc8', '#ed7a53', '#9FC569', '#bbdce3', '#9a3b1b', '#5a8022', '#2c7282'];
// function for refreshing shiftstats chart
make_chart();
function make_chart() {
$.ajax({
cache: 'false',
type: 'GET',
dataType: 'json',
url: "test.php",
success: function(data) {
var d1 = data;
var d2 = data;
//define placeholder class
var placeholder = $(".shifts-chart");
//graph options
var options = {
grid: {
show: true,
aboveData: true,
color: "#3f3f3f" ,
labelMargin: 5,
axisMargin: 0,
borderWidth: 0,
borderColor:null,
minBorderMargin: 5 ,
clickable: true,
hoverable: true,
autoHighlight: true,
mouseActiveRadius: 20
},
series: {
grow: {
active: false,
stepMode: "linear",
steps: 50,
stepDelay: true
},
lines: {
show: true,
fill: false,
lineWidth: 4,
steps: false
},
points: {
show:true,
radius: 5,
symbol: "circle",
fill: true,
borderColor: "#fff"
}
},
legend: {
position: "ne",
margin: [0,-25],
noColumns: 0,
labelBoxBorderColor: null,
labelFormatter: function(label, series) {
// just add some space to labes
return label+' ';
}
},
yaxis: { min: 0 },
xaxis: {ticks:11, tickDecimals: 0},
colors: chartColours,
shadowSize:1,
tooltip: true, //activate tooltip
tooltipOpts: {
content: "%s : %y.0",
shifts: {
x: -30,
y: -50
}
}
};
$.plot(placeholder,
[{
label: "Referrals",
data: d1,
lines: {fillColor: "#f2f7f9"},
points: {fillColor: "#88bbc8"}
},
{
label: "ProjectedVol",
data: d2,
lines: {fillColor: "#f2f7f9"},
points: {fillColor: "#88bbc8"}
}
], options);
}
});
}
});
Thanks
You'll need to change your php array creation to properly format the data into two series:
$d1 = array();
$d2 = array();
while($result = odbc_fetch_array($sql))
{
array_push($d1, array($result['Months'], $result['Referrals']));
array_push($d2, array($result['Months'], $result['ProjectedVol']));
}
$allreferrals = array($d1, $d2);
echo json_encode(($allreferrals), JSON_NUMERIC_CHECK);
This should return it as an array of arrays:
[
[[1,5981],[2,5473],[3,4974],[4,5731],[5,5891],[6,5168],[7,5551],[8,4427],[9,4617,7204],[10,4807]],
[[1,7465],[2,6962],[3,7391],[4,6985],[5,7080],[6,7136],[7,7543],[8,7242],[9,7204],[10,7642]]
]
(Hopefully I have the syntax correct, I'm not a fan of php)
Update from comment
If you are returning a slew of series, you might be better returning an associative array from PHP:
$allreferrals = array('ref' => array(), 'projVol'=> array());
while($result = odbc_fetch_array($sql))
{
array_push($allreferrals['ref'], array($result['Months'], $result['Referrals']));
array_push($allreferrals['projVol'], array($result['Months'], $result['ProjectedVol']));
}
echo json_encode(($allreferrals), JSON_NUMERIC_CHECK);
Then back in the javascript:
$.plot(placeholder,
[{
label: "Referrals",
data: data["ref"]
},
{
label: "ProjectedVol",
data: data["projVol"]
}],
options);

How to graph jqplot using datetime as yaxis and category for xaxis

var bar_fan = ['8:30','10:30'];
var bar_ticks = ['a','b'];
$(document).ready(function(){
plot2 = $.jqplot('bar_all', [bar_fan], {
seriesDefaults: {
renderer:$.jqplot.BarRenderer,
pointLabels: { show: true },
},
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: bar_ticks,
},
},
legend: {
show: true,
labels: bar_labels,
placement: 'outside'
}
});
bar_fan = ['8:30','10:30']; wont work. cause its time format.
if use value like bar_fan = [1,2]; will work.
how can I use yaxis with datetime value?
I got his working simply by adding the following to the axes configuration:
yaxis: {
renderer: $.jqplot.DateAxisRenderer
}
Now because yours are just time values, the graph will assume the current date. You may then want to specify either a minimum date or explicitly supply both date and time information, e.g., '2013-03-01 8:30AM'

javascript php mysql flot database

everyone! I have issues with regard to my x-axis. I'm using the api of flot. In my case, I'm extracting data from mysql to plot the graph. Both axes requires data to be extracted from mysql. For example, mysql will extract a data for the Y axis, say 20. My x axis will extract data from mysql of that particular time.
I tried to rewrite the script a few times, but to no conclusion. I tried attempting to create a variable, options, but it didn't work. It works only if I place the x axis statement just below y. The whole idea of creating a new variable options because I wanted to do a loop for the x-axis to continouous collect data from mysql. In the below quote, I simulated it with selected arrays.
$(function () {
var graph = [];
var power = <?php echo json_encode($data);?>;
var time = <?php echo json_encode($times);?>;
var row = <?php echo json_encode($nrow);?>;
//alert(time.toSource());
for (var i = 1; i < row; i += 1) {
//var test = time[i];
//alert(test);
//graph.push([i, power[i]]);
var hhmm = time[i].split(":");
var hh = parseInt(hhmm[0]);
var mm = parseInt(hhmm[1])/60;
var tt = hh+mm;
//var tx = hh;
graph.push([tt, power[i]]);
}
var options = {
xaxis: { ticks:[[1,time[1]],[2,time[2]],[3,time[3]],[4,time[4]],[5,time[5]],[6,time[6]],[7,time[7]],[8,time[8]]]}
};
//alert(options.toSource());
var plot = $.plot($("#placeholder"),
[ { data: graph, label: "Power" } ], {
series: {
lines: { show: true },
points: { show: true }
},
grid: { hoverable: true, clickable: true },
yaxis: { min: 0, max: 25 },
//xaxes: [ { mode: 'time' } ]
//xaxis: { mode: "time"}
//xaxis: { mode: "time",timeformat:"%H/%M" }
//xaxis: { ticks:[[1,time[1]],[2,time[2]],[3,time[3]],[4,time[4]],[5,time[5]],[6,time[6]],[7,time[7]]]}
}), options);
I have changed the options function, but it doesn't work.
var options = {
series: {
lines: { show: true },
points: { show: true }
},
grid: { hoverable: true, clickable: true },
yaxis: { min: 0, max: 25 },
for (var i = 1; i < row; i += 1)
{
xaxis: { ticks:[[i,time[i]]}
};
};
If I've surmised the format you wish for xaxis correctly, you could try the following:
var ticks = [];
for (var i = 1; i < row; i += 1)
{
ticks.push ([i, time[i]]);
}
var xaxis = {
ticks: ticks,
// ... any additional properties...
};
This will create an object xaxis with the property ticks which in turn is an array of arrays where each sub-array has two elements, the counter starting with one and the value of the time array for each i. I suppose you'll want to use code similar to this to create options:
var options = {
series: { lines: { show: true },
points: { show: true } },
grid: { hoverable: true, clickable: true },
yaxis: { min: 0, max: 25 },
xaxis: xaxis
};
You cannot use the for() statement in the object initialization, you'll have to create the xaxis array before, and use the variable name when creating the options object.

javascript php mysql flot

I encountered a new problem regarding my x-axis. My intention was to output a x-axis which indicates the time, while the y axis indicates the power. I decided to use time[i] and using graph.push([time[i], power[i]). However,my graph remains empty. I did an alert to output function and this was the result I got:
({1:"14:36", 2:"14:39", 3:"14:42", 4:"14:45", 5:"14:48", 6:"14:51", 7:"14:54", 8:"14:57"})
It's in hour: mins. What should I change to obtain a time X-axis?
$(function () {
var graph = [];
var power = <?php echo json_encode($data);?>;
var time = <?php echo json_encode($times);?>;
var row = <?php echo json_encode($nrow);?>;
//alert(time.toSource());
for (var i = 1; i < row; i += 1) {
//var test = time[i];
//alert(test);
graph.push([time[i], power[i]]);
}
var plot = $.plot($("#placeholder"),
[ { data: graph, label: "Power" } ], {
series: {
lines: { show: true },
points: { show: true }
},
grid: { hoverable: true, clickable: true },
yaxis: { min: 0, max: 25 }
});
You have to convert time from hour:mins to number
for (var i = 1; i < row; i += 1) {
//var test = time[i];
//alert(test);
var hhmm = time[i].split(":");
var hh = parseInt(hhmm[0]);
var mm = parseInt(hhmm[1])/60;
var tt = hh + mm;
graph.push([tt, power[i]]);
}
EDIT ( Eugene Wong) :
//var options = {
// xaxis: { ticks:[[1,time[1]],[2,time[2]],[3,time[3]],[4,time[4]],[5,time[5]],[6,time[6]],[7,time[7]],[8,time[8]]]}
//};
//alert(options.toSource());
var plot = $.plot($("#placeholder"),
[ { data: graph, label: "Power" } ], {
series: {
lines: { show: true },
points: { show: true }
},
grid: { hoverable: true, clickable: true },
yaxis: { min: 0, max: 25 },
xaxis: { mode: "time", timeformat:"%hh:%mm" }
//xaxis: { ticks:[[1,time[1]],[2,time[2]],[3,time[3]],[4,time[4]],[5,time[5]],[6,time[6]],[7,time[7]],[8,time[8]]]}
});
EDIT(Diode):
Even though I have created time charts before, this time setting x-axis configuration didn't work. Anyway I have fixed this by adding a tick formatter function. See the code below. 'graph' is the sample data array I used.
var graph = [[14.5, 10], [16.45, 15], [18.45, 20]];
var plot = $.plot($("#placeholder"),
[ { data: graph, label: "Power" } ], {
series: {
lines: { show: true },
points: { show: true }
},
grid: { hoverable: true, clickable: true },
yaxis: { min: 0, max: 25 },
xaxis: {
min:14,
max:20,
tickSize:0.5,
tickFormatter: function(value){
var hours = Math.floor(value);
hours = (hours < 10)?"0"+hours:hours;
var minutes = (value - hours) * 60;
minutes = (minutes < 10)?"0"+minutes:minutes;
return hours + ":" + minutes;
}
}
});
Have PHP output a Javascript timestamp instead of the already formatted date/time. Just remember a few caveats about timestamps:
PHP timestamps are seconds, whereas javascript ones are milliseconds, so multiply by 1000
flot plots in UTC time, so you may need to convert your timestamp to UTC before outputting
There is a good example of time series data on the flot website.
Remember to specify xaxis: { mode: "time" } in your flot options.

Categories