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);
Related
I am looking forward chart like this https://i.stack.imgur.com/a6dAq.png with this code
php + html:
$sql = "SELECT val1 , val2 ,t
FROM DvojeHodnoty
INNER JOIN Pristroje ON DvojeHodnoty.dev_name = Pristroje.dev_name
WHERE t>'$startdate2' AND t< '$enddate2' AND Pristroje.nazev_pristroje='$pristroj' order by val1 asc;";
$result = mysqli_query($connection, $sql);
while ($row = mysqli_fetch_array($result))
{
$t = $t.'"'.date('d.m.y H:i:s', $row['t']/1000).'",';
$hodnota = $hodnota.'"'.$row['val1'].'",';
$hodnota2 = $hodnota2.'"'.$row['val2'].'",';
}
$start = date('d.m.y', $startdate2/1000);
$end = date('d.m.y', $enddate2/1000);
$t = trim($t,",");
$hodnota = trim($hodnota,",");
$hodnota2 = trim($hodnota2,",");
}
<div id="chart-container" style="background: white">
<canvas id="chart"></canvas>
<script>
var ctx =document.getElementById("chart").getContext('2d');
var myChart = new Chart(ctx, {
type:'line',
data: {
labels: [<?PHP echo $hodnota2; ?>],
datasets:
[
{
label: '<?PHP echo $start;?> - <?PHP echo $end; ?> Přístroj: <?PHP echo $pristroj;?> ',
data: [<?PHP echo $hodnota; ?>],
backgroundColor:'transparent',
borderColor:'rgba(255,99,132)',
borderWidth: 3
}]
},
options: {
scales: {
yAxes:[{
scaleLabel: {
display: true,
labelString: 'σ',
fontSize: 20
}
}],
xAxes:[{
scaleLabel: {
display: true,
labelString: 'ε',
fontSize:20
}
}]
}
}
})
</script>
</div>
but so far I got only this https://i.stack.imgur.com/Ri8Ho.png.
I don't know how to create chart with two variables, I tried scatter but so far I am stuck with no ability to create graph with x,y line as values. Is there any easy way to create chart with two variables? If so can you help me/ give me some documentation? (I've seen one scatter chart with fix values, but I am not able to do it with php echo (with values from database) since I need to have variable values since user will choose values depends on chosen date. So far I got only 1 value (y) and two values but with text (numbers counted as text not as value) so chart looks weirdly (0,1,-1 still on same line not like normal graph showned up).
The problem was that data type was VARCHAR and for sorting it I need INT. Problem solved
I'd like to know if is possible to do that with Flot chart, because I'm not sure...
I have a table on a database with 3 rows: Date Start, Date End, Medication
Mi PHP code:
$sql = "SELECT * FROM medications ORDER BY DateStart";
$stmt = $PDO -> query($sql);
$result=$stmt -> fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row){
$dateini= $row['DateStart'];
$datend= $row['DateEnd'];
$medic= $row['Medication'];
$data1 = array(strtotime($dateini)*1000,$medic);
$data2 = array(strtotime($datend)*1000,$medic);
$data3[] = array($data1,$data2);
}
If I do:
echo json_encode($data3);
I get the array:
[[[1456531200000,"12"],[1456704000000,"12"]],[[1456531200000,"16"],[1456704000000,"16"]],[[1456617600000,"13"],[1456790400000,"13"]],[[1456704000000,"14"],[1457049600000,"14"]]]
<script>
var data3 = <?php echo json_encode($data3)?>;
$(function() {
var datasets = [
{
label: "Medication",
data: data3,
yaxis: 1,
color: "Yellow",
points: { symbol: "diamond", fillColor: "Yellow",show: true, radius: 6}
}
];
$.plot($("#flot-placeholder"), datasets ,options);
</script>
This: $.plot($("#flot-placeholder"), datasets ,options) don't plot anything, but if I do:
$.plot($("#flot-placeholder"), data3,options);
I get
It would be possible to get the graphic writing datasets (in $.plot) instead data3?
Two issues with your datasets array:
Your data3 array has multiple data series but you try to put it all into one data set object in the datasets array. Put each data series in a separate object (with its own options where neccessary).
var datasets = [{
label: "Medication",
data: data3[0],
yaxis: 1,
color: "Yellow",
points: {
symbol: diamond,
fillColor: "Yellow",
show: true,
radius: 6
}
}, {
label: "Medication",
data: data3[1],
yaxis: 1,
color: "red",
points: {
symbol: diamond,
fillColor: "red",
show: true,
radius: 6
}
}, ... ]
Flot has no build-in diamond symbol, you have to provide a function which draws a diamond.
function diamond(ctx, x, y, radius, shadow) {
var size = radius * Math.sqrt(Math.PI) / 2;
ctx.moveTo(x - size, y);
ctx.lineTo(x, y + size);
ctx.lineTo(x + size, y);
ctx.lineTo(x, y - size);
ctx.lineTo(x - size, y);
}
See this fiddle for a full working example.
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]
]
}]
});
});
Really new to Highcharts and PHP. Trying to use date from my SQL database but can get the X-axis to recognise the data as dates.
My PHP request looks like this:
<?php
mysql_connect('xxxxxxxxxxxxx.ipagemysql.com', 'xxxxx', 'xxxxxxxx') or die(mysql_error());
mysql_select_db("history") or die(mysql_error());
$result = mysql_query("SELECT * FROM eur_weekly")
or die(mysql_error());
WHILE ($row = mysql_fetch_array( $result )) {
$EUR1 [] = $row ['price'];
$EUR2 [] = $row ['date'];}
?>
Where "date" is my date column organised as follow:
31.01.2014
31.12.2013
30.11.2013
31.10.2013
30.09.2013
31.08.2013
In my HTML code I use this function that works with the rest of the data but it wont recognise the "dates" as dates data for the x-axis:
<script type="text/javascript">
$(function () {
$('#container').highcharts({
chart: {
zoomType: 'x'
},
title: {
text: 'EUR/USD '
},
xAxis: [{
type: 'datetime',
categories: [<?php echo join($EUR2,',') ?> ],
}],
yAxis: [{
labels: {
format: '{value} price',
style: {
color: '#CC33FF',
lineWidth: 0.5
}
},
}],
tooltip: { },
series: [{
name: 'EUR/USD',
color: '#4572A7',
type: 'spline',
marker:{ enabled: false},
zIndex:1,
data: [ <?php echo join($EUR1, ',') ?> ],
}]
});
});
</script>
Is there a transformation I should do? Can't find a simple example of dates from MySQL imported into Highcharts..
Thank you and best regards!
You need to parse your dates, to achieve that you can transform time to unix and multiply by 1000 in the php, other solution is parse dates in javascript.
I advice to use json_encode(), which return json in php (then load it by getJSON() in javascript), instead of inject php inside javascript.
I am trying to plot a chart (Spline) using data that is dynamically generated from PHP. The JavaScript library I am using for this purpose is HighCharts.
The PHP generates an array of values in the format like
array(
array("1304294461000",69,"1304899261000",28),
array("1304294431000",3,"1304899161000",32)
)
which I am then passing onto a javascript array using json_encode. However, when I push these values as data, it doesn't seem to be working.
For example, here's an example with relevant code snippets like -
var namesArr = <?php echo json_encode($namesArr); ?>;
var progressTrendsData = <?php echo json_encode($progressTrendsData); ?>;
var chart;
var options = {
chart: {
renderTo: 'trendsDiv',
type: 'spline'
},
series: [{
name: '',
data: []
}]
};
for(var i=0;i<namesArr.length;i++) {
options.series.push({
name: namesArr[i],
data: progressTrendsData[i]
});
}
chart = new Highcharts.Chart(options);
The options contain other relevant data needed for the chart of course.
However, the only thing the above code is doing is plotting a single value at the date January 1 irrespective of the actual data that is being pushed.
I would tend to agree w/Mark on this. It is hard to tell exactly your data is supposed to end up looking like though. Try looking at the data loading portion of the ajax data example on the highcharts demo page.
UPDATE:
Try the following pseudocode:
var chart;
var options = {
chart: {
renderTo: 'trendsDiv',
type: 'spline'
},
series: [{
name: '',
data: []
}]
};
var seriesInfo=[];
seriesInfo[0]={"name":"Series A","data":[]};
seriesInfo[1]={"name":"Series B","data":[]};
//Loop over the series and populate the data
seriesInfo[0].data.push({x:<insert Series A timestamp>,y:<insert Series A y value>});
seriesInfo[1].data.push({x:<insert Series B timestamp>,y:<insert Series B y value>});
options.series.push(seriesInfo[0]);
options.series.push(seriesInfo[1]);
chart = new Highcharts.Chart(options);