Morris Chart STacked Chart x axis redundancy - php

I've been working out a graph that will display on how many item I sell per week and per month,
I am getting what I want to display the problem is this Morris Stacked Chart displaying the week(number of weeks) redundantly. How can I solve this?
my database is in that image
PHP QUERY
$qry = $this->db->query("SELECT item_sku, sell_week, sell_month, sell FROM product_progress GROUP BY item_sku, sell_week");
while($row = mysqli_fetch_array($result)){
$chart_data .= "{ week:'".$row['sell_week']."',sku:'".$row["item_sku"]."',purchase:".$row["sell"]."},";
}
SCRIPT
Morris.Bar({
element : 'chart',
data:[<?php echo $chart_data; ?>],
xkeys: 'week',
ykeys:['purchase', 'purchase'],
labels:['Purchase', 'Week'],
lineColors: ['#1e88e5','#ff3321'],
lineWidth: '3px',
hideHover:'auto',
stacked:true
});

One line of data should contain all the info for that week.
Example: { week: 1, item_1: 10, item_2: 8, item_3: 20 }
All these columns should be declared in the ykeys of Morris.Bar.
Thus I suppose the fix would be rather in your SQL than in javascript ;-)

Related

Highcharts showing wrong time based on timezone

I am bringing in data that looks like this via PHP:
Sun Jun 26 02:00:01 EDT 2016
It becomes this variable:
$arr_dates[] = date("m/d/Y H:i", strtotime($datestr, time()));
And becomes used in Highcharts:
series: [{
name: '# users online',
data: [<?php echo "\n"; foreach ( $arr_num_users as $i ) { echo "[Date.parse('".$arr_dates[$ct]."'),".$i."],\n";$ct++; } echo "\n]"; ?>
}
So when I (EDT timezone) view it, the graph shows up correctly and the times are displayed as GMT+0.
But anyone else using a different timezone, the times are off. So someone in PDT will see a graph that is skewed by 3 hours which is incorrect. It should always be a set time, or at least accurate.
How can I fix this? setUTC did not seem to help.
Highcharts.setOptions({
global: {
useUTC: true
}
});
$('#container').highcharts({
chart: {
zoomType: 'x'
},
rangeSelector : {
selected : 1
},
.....
I've also tried without any setOptions at all, nothing changes.
This is under Highcharts v3.0.10
To be clear, the time on the chart is changing based on the users' timezone. I do not want that to happen.
You can view the issue here: http://observit.org/rffxiv.php (switch to EDT for your timezone which displays correctly, then to something else and refresh; issue will be shown)
This worked for me.
Highcharts.setOptions({
global: {
timezoneOffset: 5 * 60 //EST offset
}
});

Highcharts- show all days even if there are no values

I am using PHP and MySQL to get total amount of orders made on each day during a selected time period and then save them in a *.csv file using PHP. I generate the chart from csv file and everything is ok but I would need to include days with no orders made as well. *.csv file content is something like that:
1,05-01
1,05-02
2,05-04
1,05-06
So on the chart they appear as 1 order made on 1st of May, 1 order made on 2nd of May and then 3rd of May is skipped- I need to show it on the chart with value 0. Can it be done with jQuery/highcharts (I don't have much experience with javascript) or should I edit the PHP to create file with those values, like this:
1,05-01
1,05-02
0,05-03
2,05-04
0,05-05
1,05-06
I use the following PHP code to save the file:
$result = mysqli_query($con,"$query");
$fp = fopen('data/temp.csv', 'w');
if ($fp && $result) {
while ($row = $result->fetch_array(MYSQLI_NUM)) {
fputcsv($fp, array_values($row));
}
}
And the following script to generate the chart:
var myCategories = [];
var myData = [];
var myChart;
$(document).ready(function() {
var options = {
chart: {
renderTo: 'chart-container',
defaultSeriesType: 'column'
},
title: {
text: 'Orders received in selected days'
},
xAxis: {
title: {text: 'Date'},
categories: []
},
yAxis: {
title: {
text: 'Orders'
}
},
series: []
};
$.get('data/temp.csv', function(data) {
var lines = data.split('\n').slice(0, -1); //generated csv file has \n after last entry so there is always an empty line I have to delete
$.each(lines, function(lineNo, line) {
var items = line.split(',');
myCategories.push(items[1]);
myData.push(parseInt(items[0]));
});
options.xAxis.categories = myCategories;
options.series = [{ data: myData }];
myChart = new Highcharts.Chart(options);
});
});
Only solution I found was to create some crazy query on MySQL side (I preffer to handle that logic in PHP) it seems this cannot be done with HighCharts, so in the end I modified my PHP code a little bit to add some extra loops. If someone is interested it now looks like this:
$result2 = mysqli_query($con,"$query2");
$fp = fopen('data/temp.csv', 'w');
$dayCompare=date("n-d", strtotime($theDay)); //I know which day is the first one selected so I save it as variable #theDay
while ($row = mysqli_fetch_array($result2)) {
if ($row['Date'] !== $dayCompare){
while ($row['Date'] !== $dayCompare){ //This "while" keeps on looping till the date from database matches the day
fputcsv($fp, array('0,'.$dayCompare));
$theDay= date("Y/m/d", strtotime($theDay . "+1 day"));
$dayCompare=date("n-d", strtotime($theDay));
}
} //Rest of the code is to be executed when dates match
fputcsv($fp, array($row['Orders'].",".$row['Date']));
$theDay= date("Y/m/d", strtotime($theDay . "+1 day"));
$dayCompare=date("n-d", strtotime($theDay));
}
for ($theDay; $theDay <= $lastDay; strtotime($theDay . "+1 day")) { //I added a "for" loop to fill in the empty days if the day of last order is earlier than the last day selected/current day.
fputcsv($fp, array('0,'.$dayCompare));
$theDay= date("Y/m/d", strtotime($theDay . "+1 day"));
$dayCompare=date("n-d", strtotime($theDay));
}
This produces sample output:
"1,5-01"
"1,5-02"
"0,5-03"
"2,5-04"
"0,5-05"
"1,5-06"
The only problem that it gives me now the data is saved in the *.csv file with quotes, but I solved it by modifying the *.js file with my script changing this part:
$.each(lines, function(lineNo, line) {
var items = line.split(',');
myCategories.push(items[1]);
myData.push(parseInt(items[0]));
});
To this:
$.each(lines, function(lineNo, line) {
var items = line.split(',');
myCategories.push(items[1].replace(/"/g,""));
myData.push(parseInt(items[0].replace(/"/g,"")));
});
Thanks to trimming the quote marks the output is as expected. Variables with dates are still quite elaborated but it seems it has to be like that since PHP has problems recognizing short dates when it is about doing math equations, and I also hope to modify that triple loop someday but this will have to wait at least till next deployment.
In the end I added one more loop to loop through the empty days when the last day selected is later than the day of last order, for example if 9th of May was selected and last order was on 7th there will be 2 lines added with 0 values for 8th and 9th.

Getting Data from PHP, JSON Highcharts?

Hi I am trying to get data from MySql table and show the data in Highcharts by using PHP and Json
I have try the example from internet and it is working fine but when I try to get data from my file it show nothing.
What I am trying to do:
I am creating table of office attendance system and trying to show record day by day. So at y axis I want to count names of employees and x axis the date of attendance.
Problem: Nothing Is show from mu json.
Here is what my Json looks like:
[["Hamza","07\/04\/2014"],
["Junaid","07\/04\/2014"],
["Usman","07\/04\/2014"],
["Rajab","07\/04\/2014"],
["Hamza","08\/04\/2014"],
["Junaid","08\/04\/2014"],
["Usman","08\/04\/2014"],
["Rajab","08\/04\/2014"]]
I am having to value names and dates.
My PHP which is creating my Json code:
// Set the JSON header
header("Content-type: text/json");
$result = mysqli_query($con,"SELECT * FROM attendence");
$a=array();
while($row = mysqli_fetch_array($result)) {
$row['name'] . "\t" . $row['date']. "\n";
$b=array();
array_push($b,$row['name']);
array_push($b,$row['date']);
array_push($a,$b);
}
echo json_encode($a);
and this is my Jquery code:
$(function() {
$.getJSON('highchart.php', function(data) {
// Create the chart
$('#chart').highcharts('StockChart', {
rangeSelector : {
selected : 1,
inputEnabled: $('#chart').width() > 480
},
title : {
text : 'Attendence'
},
series : [{
name : 'Empolyees',
data : data,
tooltip: {
valueDecimals: 2
}
}]
});
});
});
In the json_encode() you need to use JSON_NUMERIC_CHECK flag to avoid use string in your JSON
In the highstock you need to have timestamps and value, not name and date.
Dates should be timestamp, and as first element in array, not second as you have.
If you want to get a count of all people on a given day, you need to write a SQL query that returns that information. Assuming that date field is a datetime type and name is of varchar type:
SELECT COUNT(name) FROM attendence GROUP BY DATE(date);
perhaps you need to define what kind of data your x-axis will have
take a look at this fiddle (taken from highcharts website)
$(function () {
$('#container').highcharts({
xAxis: {
type: 'datetime'
},
series: [{
data: [
[Date.UTC(2010, 0, 1), 29.9],
[Date.UTC(2010, 2, 1), 71.5],
[Date.UTC(2010, 3, 1), 106.4]
]
}]
});
});

Get json data into Highcharts scatter plot

I cannot get Highcharts to graph a scatter plot of 2 series. Actually, the graph isn't even showing up. Please help me determine what I'm doing wrong. I cannot find a scatter plot example to go off of and I am very new to this. I've got json data from a php file that looks like:
[[65,44],[66,37],[67,42],[68,55],[65,50],[65,41],[65,41],[68,41],[69,42],[70,47],[69,55],[67,45],[67,49],[67,53],[67,49],[68,51],[68,55],[68,57],[70,53],[69,66],[68,54],[69,52],[68,48]][[75,36],[72,42],[75,44],[69,56],[72,40],[73,37],[77,34],[77,40],[74,50],[77,45],[77,43],[75,47],[73,52],[73,50],[75,44],[72,54],[71,57],[72,57],[74,55],[74,54],[75,47],[78,45],[75,43]]
This should be two series in an (x,y) format. I want to graph these on a scatter plot in HighCharts. My HighCharts code is:
<script type="text/javascript">
$(function () {
var chart;
$(document).ready(function() {
$.getJSON("comfortgb1b.php", function(json) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container4',
type: 'scatter',
marginRight: 175,
marginBottom: 50
},
title: {
text: 'Comfort Level',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
title: {
enabled: true,
text: 'Temp (F)'
},
min: 60,
max: 85,
startOnTick: true,
endOnTick: true,
showLastLabel: true
},
yAxis: {
title: {
text: 'Humidity (%RH)'
},
min: 30,
max: 100
},
plotOptions: {
scatter: {
marker: {
radius: 5,
states: {
hover: {
enabled: true,
lineColor: 'rgb(100,100,100)'
}
}
},
states: {
hover: {
marker: {
enabled: false
}
}
},
tooltip: {
headerFormat: '<b>{series.name}</b><br>',
pointFormat: '{point.x} F, {point.y} %RH'
}
},
series: [{
name: 'Night',
data: json(1)
}, {
name: 'Night',
data: json(2)
});
});
});
});
</script>
Thanks in advance!
The php file that is creating the json data is below. How would I separate these arrays with a comma?
$result1 = mysql_query("SELECT round(AVG(d_internal_duct_return),0) AS 'avg_return', round(AVG(d_evap_pre_humidity),0) AS 'avg_hum' FROM pheom.pheom_gb WHERE timestamp between subdate(curdate(), interval 2 month) and curdate() AND HOUR(Timestamp) NOT BETWEEN 9 AND 22 GROUP BY DAY(Timestamp) ORDER BY Timestamp");
$ret1 = array();
while($item = mysql_fetch_array($result1)) {
$avg_return1 = $item['avg_return'];
$avg_hum1 = $item['avg_hum'];
$ret1[] = array($avg_return1,$avg_hum1);
}
$result2 = mysql_query("SELECT round(AVG(d_internal_duct_return),0) AS 'avg_return', round(AVG(d_evap_pre_humidity),0) AS 'avg_hum' FROM pheom.pheom_gb WHERE timestamp between subdate(curdate(), interval 2 month) and curdate() AND HOUR(Timestamp) BETWEEN 9 AND 22 GROUP BY DAY(Timestamp) ORDER BY Timestamp");
$ret2 = array();
while($item = mysql_fetch_array($result2)) {
$avg_return2 = $item['avg_return'];
$avg_hum2 = $item['avg_hum'];
$ret2[] = array($avg_return2,$avg_hum2);
}
echo json_encode($ret1, JSON_NUMERIC_CHECK);
echo json_encode($ret2, JSON_NUMERIC_CHECK);
Not sure about this, but at first glance I think the array returned from the php file requires an additional square bracket outside it in order to be parsed as proper json. Currently it is:
[[65,44],[66,37]..][[75,36],[72,42]..]
From what I know, this is just two arrays. What you want is to enclose these arrays within an array. Try changing this to:
[[[65,44],[66,37]..],[[75,36],[72,42]..]]
That is, add an extra square bracket outside and separate the two arrays using a comma.
In addition, here:
series: [{
name: 'Night',
data: json(1)
}, {
name: 'Night',
data: json(2)
});
json(1) and json(2) are interpreted as function calls. You should instead use:
series: [{
name: 'Night',
data: json[0]
}, {
name: 'Night',
data: json[1]
});
EDIT ---- Edited as per OP edits
Also as requested, in order to add the commas and proper formatting, the php file can be changed at the last two lines as follows:
echo "[".json_encode($ret1, JSON_NUMERIC_CHECK).",";
echo json_encode($ret2, JSON_NUMERIC_CHECK)."]";
You have several things giving you problems. See this fiddle: http://jsfiddle.net/nbwN9/1/
First, I don't think your json is in the proper format for a 2 series plot. You have two arrays of data just butted up to each other rather than in another array. The linked fiddle corrects that (and stuffs it into a var since the getJSON() call will fail within jsFiddle). Each point is an array of (x,y) coords. Each series.data is an array of points. Your json will need to be an array of series.data arrays. So we're looking at nested arrays 3 deep.
Second, you seem to have a malformed set of chart options. Most notable is that your series node (with name and data) is inside your plotOptions node when it should be outside of it. And that series node is not terminated properly.
Third, once you get your json data and your chart options formatted correctly, accessing the json array is done like so:
series: [{
name: 'Night',
data: json[0]
}, {
name: 'Day',
data: json[1]
}]
The array is 0-based (so the first record will be indexed with a 0, second record with a 1, etc) and is access using the brackets [] not parentheses ()
Sorry, I renamed one of your series to "Day" so I could see the difference in the chart.
As far as the PHP script... try this:
$result1 = mysql_query("SELECT round(AVG(d_internal_duct_return),0) AS 'avg_return', round(AVG(d_evap_pre_humidity),0) AS 'avg_hum' FROM pheom.pheom_gb WHERE timestamp between subdate(curdate(), interval 2 month) and curdate() AND HOUR(Timestamp) NOT BETWEEN 9 AND 22 GROUP BY DAY(Timestamp) ORDER BY Timestamp");
$ret1 = array();
while($item = mysql_fetch_array($result1)) {
$avg_return1 = $item['avg_return'];
$avg_hum1 = $item['avg_hum'];
$ret1[] = array($avg_return1,$avg_hum1);
}
$result2 = mysql_query("SELECT round(AVG(d_internal_duct_return),0) AS 'avg_return', round(AVG(d_evap_pre_humidity),0) AS 'avg_hum' FROM pheom.pheom_gb WHERE timestamp between subdate(curdate(), interval 2 month) and curdate() AND HOUR(Timestamp) BETWEEN 9 AND 22 GROUP BY DAY(Timestamp) ORDER BY Timestamp");
$ret2 = array();
while($item = mysql_fetch_array($result2)) {
$avg_return2 = $item['avg_return'];
$avg_hum2 = $item['avg_hum'];
$ret2[] = array($avg_return2,$avg_hum2);
}
echo json_encode(array($ret1,$ret2), JSON_NUMERIC_CHECK);

Multiple graphs in php loop

I have a problem with google charts. I developed a web page with 5 (generated with php) and 5 ID for each :
echo "<div id = \"ID\" style=\"display:none;\">"
I also have 5 json arrays with all the information. I show in each the data in a table but I would like also show a graph with my data.
I tried to do in this way (but it doesn't work):
for ($i = 0; $i<$n;$i++){
$jsonTable = json_encode(${'table'.$Result_array[$i][1]});
$ID = $Result_array[$i][1]; //ID for the div
echo "<script type=\"text/javascript\">
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart());
function drawChart() {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(".$jsonTable.");
var options = {
title: 'Company Performance',
hAxis: {title: 'L value', titleTextStyle: {color: 'red'}, gridlines:{count:10} },
vAxis: {
title: \"I rms\",
maxValue:1.5,
gridlines:{count:10}
}
};
// Instantiate and draw our chart, passing in some options.
// Do not forget to check your div ID
var chart = new google.visualization.ColumnChart(document.getElementById('".$ID."'));
chart.draw(data, options);
}
}
</script>";
}
If I use this code only for 1 table, works fine, but when I use a loop and try to generate multiple graphs, it doesn't work.
Anyone could help me? thanks!
P.S: Maybe I also have to explain that, first of all, I have a table with my 5 results, and when I click, I have a onclik function to unhide the appropiate . This works always (with graphs and without it) but never display the graphs....
Where are the 5 ids you are looping through only one id
var chart = new google.visualization.ColumnChart(document.getElementById('".$ID."'));
It should be like this
var chart = new google.visualization.ColumnChart(document.getElementById('".$ID."_".$i"'));
and add the div like
echo "<div id = \"ID_0\" style=\"display:none;\">"
echo "<div id = \"ID_1\" style=\"display:none;\">"
echo "<div id = \"ID_2\" style=\"display:none;\">"
echo "<div id = \"ID_3\" style=\"display:none;\">"
echo "<div id = \"ID_4\" style=\"display:none;\">"

Categories