getting data in specified format for flot bar charts - javascript

I am trying ti plot a flot bar chart and I am unable to fetch the data in the way which flot requires.please correct me where I am doing mistake? My query returns results like
A-250,B-100,C-300 etc.
My code is shown below :
<?php
require_once('../../Connections/finalkms.php');
mysql_select_db($database_finalkms, $finalkms);
$query_getmaincatdetails = "SELECT `EquipmentMainCatagory`,count(`EquipmentMainCatagory`) FROM `assetinfo` group by EquipmentMainCatagory HAVING EquipmentMainCatagory !=''";
$getmaincatdetails = mysql_query($query_getmaincatdetails, $finalkms) or die(mysql_error());
$row_getmaincatdetails = mysql_fetch_assoc($getmaincatdetails);
$totalRows_getmaincatdetails = mysql_num_rows($getmaincatdetails);
for ($i = 1; $i <=$totalRows_getmaincatdetails ; $i++)
{
$ticks[] = array( $i,(int)$row_getmaincatdetails['EquipmentMainCatagory']);
$data[] = array( $i,(int)$row_getmaincatdetails['count(`EquipmentMainCatagory`)']);
}
$jsonTable = json_encode(array("data" => $data, "ticks" => $ticks));
?>
In Js:
<script type="text/javascript">
var data1 =<?php echo $jsonTable;?>;
var options = {
series: {
bars: {
show: true
}
}
};
$(document).ready(function () {
$.plot($("#placeholder"),options);
});
</script>
<div id="placeholder"></div>

PHP looks ok, on the JS side, you need something like this:
<script type="text/javascript">
var dataAndTicks = <?php echo $jsonTable;?>;
var options = {
series: {
bars: {
show: true
}
},
xaxis: {
ticks: dataAndTicks['ticks']
}
};
$(document).ready(function () {
$.plot($("#placeholder"),dataAndTicks['data'], options);
});
</script>

For flot charts the syntax is as follows:
var plot = $.plot(placeholder, data, options)
Example
var options = {
series: {
lines: { show: true },
points: { show: true }
}
};
var d2 = [[0, 3], [4, 8], [8, 5], [9, 13]];
$.plot("#placeholder", [ d2 ], $options);

Related

Highcharts loaded via ajax, issue to dynamically create yAxis

I have a page that dynamically updates a HighCharts graph from a multiselect dropdown.
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/series-label.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
</head>
<body>
<!-- FIELDS -->
<div id="fields">
<form method="post" action="">
<select id="f" name="f[]" multiple>
<option value="rss1" select>1RSS(dB)</option>
<option value="rss2">2RSS(dB)</option>
<option value="rqly">RQly(%)</option>
<option value="rsnr">RSNR(dB)</option>
</select>
</form>
</div>
<!-- GRAPH -->
<div id="graph">No selection</div>
<script>
var updateChart = function(json) {
// console.log(json)
var options = {
chart: {
renderTo: 'graph',
type: 'line',
zoomType: 'x'
},
title: { text: null },
plotOptions: {
series: {
label: {
connectorAllowed: false
},
pointStart: 0
}
},
series: []
}
options.series = json;
var chart = new Highcharts.Chart(options);
// update yaxis
for (i=0; i<json.length; i++) {
if(i==0) {
// it seems that a yAxis already exist when graph is initialized. Did not find a smarter way to destroy it...
chart.yAxis[0].update({ title: { text: json[i].name }});
} else {
chart.addAxis({ title: { text: json[i].name } });
}
}
}
$(document).ready(function() {
$('#f').change(function() {
var requestParams = { f: $('#f').val() };
$.post('analysisajax.php', requestParams, updateChart);
});
});
</script>
</body>
</html>
Now, my analysisajax.php file looks like this:
<?php
header("Content-type: text/json");
// Initialize the session
session_start();
// Include config file
require_once "config.php";
$jsonObject = array();
$yaxis = 0;
foreach($_POST["f"] as $v) {
$data = array();
$sql = "SELECT $v FROM log WHERE id_user = " . $_SESSION["id_user"];
$result = $link->query($sql);
while($row = $result->fetch_row()) {
$data[] = $row[0];
}
$jsonObject[] = array(
"name" => $v,
"data" => $data,
"yAxis"=>$yaxis
);
$yaxis++;
}
$myJSON = json_encode($jsonObject, JSON_NUMERIC_CHECK);
echo $myJSON;
// Close connection
mysqli_close($link);
?>
When I'm selecting 1 value from the form, the graph loads without problem, but as soon as more than 1 value is selected from the dropdown, the graph fails with the following trace:
highcharts.src.js:498 Uncaught Error: Highcharts error #18: www.highcharts.com/errors/18
at Object.a.error (highcharts.src.js:498)
at highcharts.src.js:32669
at Array.forEach (<anonymous>)
at r.<anonymous> (highcharts.src.js:32621)
at a.fireEvent (highcharts.src.js:2635)
at r.bindAxes (highcharts.src.js:32618)
at r.init (highcharts.src.js:32482)
at a.Chart.initSeries (highcharts.src.js:26913)
at highcharts.src.js:28765
at Array.forEach (<anonymous>)
I feel that the issue is coming from my dynamic construction of yAxis but can't find a way to make it work. Any idea? Thanks a lot.
I eventually made it work with the following solution:
In the analysisajax.php script, I no longer generate the yaxis. I only send name and data.
The code to generate the graph now looks like this:
var updateChart = function(json) {
//console.log(json)
var options = {
chart: {
renderTo: 'graph',
type: 'line',
zoomType: 'x'
},
title: { text: null },
yAxis:[],
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'bottom'
},
plotOptions: {
series: {
label: {
connectorAllowed: false
},
pointStart: 0
}
},
series: [],
tooltip: { shared: true }
}
var chart = new Highcharts.Chart(options);
// update axis and series
for (i=0; i<json.length; i++) {
// add axis
chart.addAxis({ title: { text: json[i].name } });
// add serie
var a = chart.series.length;
var seriesOptions = {
name: json[i].name,
data: json[i].data,
yAxis: a
}
chart.addSeries(seriesOptions,true);
chart.options.series.push(seriesOptions);
}
}
$(document).ready(function() {
$('#f').change(function() {
var requestParams = { f: $('#f').val() };
$.post('analysisajax.php', requestParams, updateChart);
//return false;
});
});

Reading MySQL data into highstocks

So this is the first time i have really worked with high charts i have some data reading into high charts from my MySQL database, but the next step is to try and set up a high stocks chart. Whenever i try and use the same method as i did with high charts the chart doesn't work? This is what i want to aim for - StockChartDemo
PHP Code:
$conn = new mysqli($servername, $username, $password, $dbName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "(SELECT date AS time ,IFNULL(RH,'null')AS humidity
FROM test ORDER BY date DESC LIMIT 20) ORDER BY time ASC";
$result = $conn->query($sql);
if ($result->num_rows>0){
$count =0;
echo '[';
while($row=$result->fetch_assoc()){
echo '['.$row["time"].',' .$row["humidity"].']';
$count++;
if ($count<"20"){
echo ',';
}
}
echo ']';
}else{
echo "[[],[]]";
}
$conn->close();
?>
html & jQuery:
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="highstock.js"></script>
</head>
<script type="text/javascript">
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
var options = {
chart: {
renderTo: 'tempcontainer',
alignTicks: false,
height:320,
},
rangeSelector: {
selected: 1
},
title: {
text: 'Relative humidity'
},
series: [{
type: 'column',
name: 'Humidity',
data: json,
dataGrouping: {
units: [[
'month', // unit name
[1] // allowed multiples
], [
'week',
[1, 2, 3, 4, 6]
]]
}
}]
}
$.getJSON("stockdata.php", function(json) { /*Get the array data in data.php using jquery getJSON function*/
options.series[0].data = json; /*assign the array variable to chart data object*/
chart = new Highcharts.stockChart(options); /*create a new chart*/
});
function refreshChart(){ /*function is called every set interval to refresh(recreate the chart) with the new data from data.php*/
setInterval(function(){
$.getJSON("stockdata.php", function(json) {
options.series[0].data = json;
chart = new Highcharts.stockChart(options);
});
},60000);
}
});
</script>
<div id="tempcontainer"></div>
Presuming your query is returning the correct data you want. (I'm not up for mocking it out to test your query)
You should switch out the following code, and all that in-between.
if ($result->num_rows>0){
//snip
}
To use json_encode() instead.
$series = [];
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$series[] = [
$row["time"],
$row["humidity"]
];
}
}
header('Content-Type: application/json');
exit(json_encode($series));

data not displaying in google barchart

I am trying to display graph using google api. Even though i get result in array, it is not getting displayed in chart.
here is my code
<?php
$query = "SELECT
MONTHNAME(last_modified) as Month,
SUM(before_order_line_items.total) AS Quotes,
COUNT(orders.order_id) AS Qcnt
FROM orders
INNER JOIN before_order_line_items
ON orders.sales_order_id = before_order_line_items.sales_order_id
WHERE order.order_quote='Quote' AND orders.authorise = 'Yes'
GROUP BY MONTH(orders.last_modified)
ORDER BY YEAR(orders.last_modified)
";
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) {
$myurl[] = "['".$row['Month']."', ".$row['Quotes'].", ".$row['Qcnt']."]";
}
?>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Month', 'Quotes', 'Counts'],
<?php
echo implode(",", $myurl);
?>
]);
var options = {
title: 'Orders',
vAxis: {
title: '',
titleTextStyle: {
color: 'red'
}
}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<div id="chart_div" style="height: 400px;"></div>
When i check the date i am getting the date for Qcnt also
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Month', 'Quotes', 'Counts'],
['May', 23299.00, 2] ]);
But it is not getting displayed in graph. Only Quote amount is getting displayed.
the value for 'Counts' is too small
and simply isn't visible due to the scale of the chart...
you could assign the 'Counts' series to a second y-axis...
series: {
1: {
targetAxisIndex: 1
}
},
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Month', 'Quotes', 'Counts'],
['May', 23299.00, 2],
['June', 23200.00, 2]
]);
var options = {
series: {
1: {
targetAxisIndex: 1,
}
},
title: 'Orders',
vAxis: {
title: '',
titleTextStyle: {
color: 'red'
}
}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Post request inside php code var anidade

I am working with Dygraphs to chart Arduino sensor data.I need to get a subtract between two data so i am using php inside a script function but it doesn't work.It is possible to include
<script type="text/javascript">
var csv = [
'<?php
$row = 1;
if (($handle = fopen("https://api.thingspeak.com/channels/***/feed.csv?key=***&start=<?php echo $_POST['day_ini'];?>%20<?php echo $_POST['hour_ini'];?>&end=<?php echo $_POST['day_end'];?>%20<?php echo $_POST['hour_end'];?>", "r")) !== FALSE) {
...
?>','2015-11-02 20:54:50 UTC,1049703,5,5'
];
This is all my function code:
<script type="text/javascript">
var csv = [
'<?php
$row = 1;
if (($handle = fopen("https://api.thingspeak.com/channels/***/feed.csv?key=***&start=2015-11-02%2020:50:45&end=2015-11-02%2021:50:45", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 50, ",")) !== FALSE) {
if($row == 1){ $row++; continue; }
$num = count($data);
for ($c=0; $c < $num; $c++) {
if(strpos($data[$c], 'Finished') !== false) {
$c++;
echo $data[$c] . "," ; }
Else{
echo $data[$c] . "," ;
}
}
}
fclose($handle);
}
?>','2015-11-02 20:54:50 UTC,1049703,5,5'
//... etcetera
];
function getPairDifference(pair) {
//"pair" is a zero-based integer.
// "0" will return a difference between csv rows "0" & "1"
// "1" will return a difference between csv rows "1" & "2"
// etcetera...
var firstVal = parseInt(csv[pair].split(",")[3]);
var secondVal = parseInt(csv[pair + 1].split(",")[3]);
return firstVal - secondVal;
}
for (var i = 0; i < csv.length; i += 1) {
// Demo code to visualize numbers.
// Actual function call of interest is simply "getPairDifference( i )"
var plot = getPairDifference(i);
// $("<div></div>").text(plot).appendTo("body");
$(function() {
$("#chart3").chart({
template: "line_basic_6",
tooltips: {
serie1: [plot],
width:20,
height:15,
},
values: {
serie1: [plot]
},
labels: ["Period 1","Period 2"],
defaultSeries: {
type: "bar",
stacked: true
},
series: {
serie3: {
type: "line",
stacked: false,
axis: "r"
}
},
axis: {
r: {
max: 100,
suffix: "%"
}
}
});
});
$.elycharts.templates['line_basic_6'] = {
type: "line",
margins: [10, 40, 40, 30],
defaultSeries: {
highlight: {
newProps: {
r: 8,
opacity: 1
},
overlayProps: {
fill: "white",
opacity: 0.2
}
}
},
series: {
serie1: {
color: "90-#003000-#009000",
tooltip: {
frameProps: {
stroke: "green"
}
}
},
},
defaultAxis: {
labels: true
},
axis: {
x: {
labelsRotate: 0,
labelsProps: {
font: "11px Verdana"
}
}
},
features: {
grid: {
draw: true,
forceBorder: true,
ny: 5
}
},
barMargins: 180
};
}
</script>
Thanks in advance.
no need to echo like that and you are using <?php inside another <?php before closing that.
<script type="text/javascript">
var csv = [
'<?php
$row = 1;
if (($handle = fopen("https://api.thingspeak.com/channels/***/feed.csv?key=***&start={$_POST['day_ini']}%20{$_POST['hour_ini']}&end={$_POST['day_end']}%20{$_POST['hour_end']}", "r")) !== FALSE) {
}
?>', '2015-11-02 20:54:50 UTC,1049703,5,5'
];
</script>
And i am not sure of }, please check that once.
You have missunderstood something about PHP and Javascript.
Javascript gets sended to the Client, so it works in the Browser and also get's executed.
PHP altough gets executed on the Server first, there lies your problem, you can't execute on the Client something that needs to be done by a Server.

Two google bar charts not working in one page

I am not able to show two bar charts in one page. I have tried both ways, implementing these in two different <script> sections in and in one <script> section also. If one is shown if I make changes to <div> id, another is not shown and vice versa but both of them not shows at one time. I have also tried with visualization version change. When I see page source, there I see all the data for both graphs, but only graph is not created. What might be the problem. I have tried a lot, but not able to debug, in last I am here. Below is my code.
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['bar']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data1 = google.visualization.arrayToDataTable([
['Metric Tonnes', 'HSFO', 'LSFO', 'MGO'],
<?php
foreach ($log_book_discrepancy as $log_book)
{
?>
["<?php echo trim($log_book->type_of_vessel); ?>", <?php echo trim($log_book->fuel_hsfo); ?>, <?php echo trim($log_book->fuel_lsfo); ?>, <?php echo trim($log_book->fuel_mgo); ?> ],
<?php
}
?>
]);
// Create the data table.
var data2 = google.visualization.arrayToDataTable([
['Metric Tonnes', 'HSFO', 'LSFO', 'MGO'],
<?php
foreach ($bunker_found as $bunker)
{
?>
["<?php echo trim($bunker->type_of_vessel); ?>", <?php echo trim($bunker->fuel_hsfo); ?>, <?php echo trim($bunker->fuel_lsfo); ?>, <?php echo trim($bunker->fuel_mgo); ?> ],
<?php
}
?>
]);
// Set chart options
var options1 = {
chart: {
title: 'Log Book Discrepancy',
subtitle: 'HSFO, LSFO, and MGO',
}
};
// Set chart options
var options2 = {
chart: {
title: 'Bunkers Found',
subtitle: 'HSFO, LSFO, and MGO',
}
};
// Instantiate and draw our chart, passing in some options.
var chart1 = new
google.charts.Bar(document.getElementById('log_book_discrepancy'));
chart1.draw(data1, options1);
var chart2 = new
google.charts.Bar(document.getElementById('bunkers_found'));
chart2.draw(data2, options2);
}
</script>
<div id="log_book_discrepancy" style="width:100%; height:340px;"></div>
<div id="bunkers_found" style="width:100%; height:340px;"></div>
And my both arrays become like:
$log_book_discrepancy is like:
Array
(
[0] => stdClass Object
(
[type_of_vessel] => BULK CARRIER
[fuel_hsfo] => 30
[fuel_lsfo] => 40
[fuel_mgo] => 40
)
[1] => stdClass Object
(
[type_of_vessel] => OIL TANKER
[fuel_hsfo] => 60
[fuel_lsfo] => 40
[fuel_mgo] => 45
)
)
And $bunker_found array is like:
Array
(
[0] => stdClass Object
(
[type_of_vessel] => BULK CARRIER
[fuel_hsfo] => 10
[fuel_lsfo] => 40
[fuel_mgo] => 40
)
[1] => stdClass Object
(
[type_of_vessel] => CHEMICAL TANKER
[fuel_hsfo] => 50
[fuel_lsfo] => 40
[fuel_mgo] => 55
)
)
This is solution without PHP with the given data, first chart with option: "isStacked: true":
google.load('visualization', '1', {packages: ['corechart', 'bar']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data1 = google.visualization.arrayToDataTable([
['Metric Tonnes', 'HSFO', 'LSFO', 'MGO'],
['BULK CARRIER', 30, 40, 40],
['OIL TANKER', 60, 40, 45]
]);
var data2 = google.visualization.arrayToDataTable([
['Metric Tonnes', 'HSFO', 'LSFO', 'MGO'],
['BULK CARRIER', 10, 40, 40],
['CHEMICAL TANKER', 50, 40, 55]
]);
var options1 = {
title: 'Log Book Discrepancy',
chartArea: {width: '50%'},
isStacked: true,
hAxis: {
title: 'HSFO, LSFO, and MGO',
minValue: 0,
},
};
var options2 = {
title: 'Bunkers Found',
chartArea: {width: '50%'},
hAxis: {
title: 'HSFO, LSFO, and MGO',
minValue: 0,
},
};
var chart1 = new google.visualization.BarChart(document.getElementById('log_book_discrepancy'));
chart1.draw(data1, options1);
var chart2 = new google.visualization.BarChart(document.getElementById('bunkers_found'));
chart2.draw(data2, options2);
}
https://jsfiddle.net/mblenton/pmeh4hr9/2/
or with MaterialChart:
https://jsfiddle.net/mblenton/gp12p37w/2/
Try this:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {packages: ['corechart', 'bar']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data1 = google.visualization.arrayToDataTable([
['Metric Tonnes', 'HSFO', 'LSFO', 'MGO'],
<?php
foreach ($log_book_discrepancy as $log_book)
{
?>
["<?php echo trim($log_book->type_of_vessel); ?>", <?php echo trim($log_book->fuel_hsfo); ?>, <?php echo trim($log_book->fuel_lsfo); ?>, <?php echo trim($log_book->fuel_mgo); ?> ],
<?php
}
?>
]);
// Create the data table.
var data2 = google.visualization.arrayToDataTable([
['Metric Tonnes', 'HSFO', 'LSFO', 'MGO'],
<?php
foreach ($bunker_found as $bunker)
{
?>
["<?php echo trim($bunker->type_of_vessel); ?>", <?php echo trim($bunker->fuel_hsfo); ?>, <?php echo trim($bunker->fuel_lsfo); ?>, <?php echo trim($bunker->fuel_mgo); ?> ],
<?php
}
?>
]);
// Set chart options
var options1 = {
chart: {
title: 'Log Book Discrepancy',
subtitle: 'HSFO, LSFO, and MGO',
}
};
// Set chart options
var options2 = {
chart: {
title: 'Bunkers Found',
subtitle: 'HSFO, LSFO, and MGO',
}
};
// Instantiate and draw our chart, passing in some options.
var chart1 = new google.visualization.BarChart(document.getElementById('log_book_discrepancy'));
chart1.draw(data1, options1);
var chart2 = new google.visualization.BarChart(document.getElementById('bunkers_found'));
chart2.draw(data2, options2);
}
</script>
<div id="log_book_discrepancy" style="width:100%; height:340px;"></div>
<div id="bunkers_found" style="width:100%; height:340px;"></div>

Categories

Resources