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>
Related
I'm new in Apexcharts, and I try to make a pie chart with data, getting from mysql database. This is the php-file named "get_types_chart.php"
$year = date('Y');
$month = date('m');
$graf = PDO()->prepare("SELECT COUNT(tickets.id) AS cid, types.ticket_type AS type_name FROM tickets LEFT JOIN types ON tickets.type=types.id WHERE tickets.arch=0 AND tickets.status NOT IN (2, 4) AND MONTH(tickets.date_create)=:month AND YEAR(tickets.date_create)=:year GROUP BY types.ticket_type");
$graf->execute([':year' => $year,
':month' => $month]);
$arrData = array();
while($row = $graf->fetch(PDO::FETCH_LAZY)) {
array_push($arrData, array(
"labels" => $row->type_name,
"series" => $row->cid
)
);
}
$jsonEncodedData = json_encode($arrData);
header('Content-Type: application/json');
echo $jsonEncodedData;
And this is the js-code:
var url3 = 'charts/get_types_chart.php';
var options3 = {
series: [],
chart: {
width: 380,
type: 'pie',
},
title: {
text: '<?php echo lang('MON_STAT_year'); ?>',
floating: true,
align: 'center'
},
labels: [],
responsive: [{
breakpoint: 480,
options: {
chart: {
width: 200
},
legend: {
position: 'bottom'
}
}
}]
};
var chart3 = new ApexCharts(document.querySelector("#chart3"), options3);
chart3.render();
$.getJSON(url3, function(response) {
chart3.updateSeries([{
name: '<?php echo lang('DASH_STAT_month_all'); ?>',
data: response
}])
});
Finally I get empty pie. Please hel me to make a correct json.
$days = ["Monday","Tuesday","Wednesday"];
$rates = [40,60,80];
$profit = [];
foreach($days as $day => $value){
foreach($rates as $rate){
$netprofit = $rate* 20;
$profit[$value] = [$rate=> $netprofit];
}
}
$usersChart = new UserChart;
$usersChart->labels($days);
foreach($profit as $key => $value){
$data = array();
foreach ($value as $values){
$data[] = $values;
}
$usersChart->dataset($key, 'line', collect($data));
}
I want to show this array into Chartjs Line Graph. I want the x axis to be the 40,60,80. Y axis to be 800, 1200, 1600. The Dataset or Lines should be Monday, Tuesday and Wednesday.
Right now i get Monday, Tuesday and Wednesday as x axis and Line. 600,800 etc are on y axis.
Array
(
[Monday] => Array
(
[40] => 800
[60] => 1200
[80] => 1600
)
[Tuesday] => Array
(
[40] => 800
[60] => 1200
[80] => 1600
)
[Wednesday] => Array
(
[40] => 800
[60] => 1200
[80] => 1600
)
)
keep your array as it is and convert it to JSON object and then echo it inside Javascript, javascript have to be inside php file to run, not in external javascript file.
notice that there is PHP code in this example and i have put <?php echo $json; ?> inside the javascript code.
<html>
<head>
<style>body{width: 800px;}</style>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
</head>
<body>
<div>
<canvas id="myChart" width="700px" height="300px"></canvas>
</div>
<?php
$array = array(600, 800, 1200, 1800);
$json = json_encode($array);
?>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
labels: ["20", "40", "60", "80"],
datasets: [
{
label: 'Monday',
borderColor: "#FF9F40",
data: <?php echo $json; ?>,
},
{
label: 'Tuesday',
borderColor: "#FF6384",
data: [600, 800, 1200, 1800]
},
{
label: 'Wednesday',
borderColor: "#219151",
data: [600, 800, 1200, 1800]
}
]
},
// Configuration options go here
options: {}
});
</script>
</body>
</html>
Im trying to display 2 different pie chart which takes value from php database. but problem is when I do the second pie chart, the first pie chart would not show but will show the second pie chart, means it works 1 at the time.
Where is the error?
1st code for pie chart
?php
$dataPoints = array();
//Best practice is to create a separate file for handling connection to database
try{
// Creating a new connection.
// Replace your-hostname, your-db, your-username, your-password according to your database
$link = new \PDO( 'mysql:host=localhost;dbname=OISC;charset=utf8mb4', //'mysql:host=localhost;dbname=canvasjs_db;charset=utf8mb4',
'root', //'root',
'', //'',
array(
\PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_PERSISTENT => false
)
);
$handle = $link->prepare("SELECT Gender, COUNT(Gender) AS totalUser FROM register GROUP By Gender");
$handle->execute();
$result = $handle->fetchAll(\PDO::FETCH_OBJ);
foreach($result as $row){
array_push($dataPoints, array("x"=> $row->Gender, "y"=> $row->totalUser));
}
$link = null;
}
catch(\PDOException $ex){
print($ex->getMessage());
}
?>
1 JavaScript for pie chart
<script>
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
exportEnabled: true,
theme: "light1", // "light1", "light2", "dark1", "dark2"
title:{
text: "Gender Pie Chart"
},
data: [{
type: "pie", //change type to bar, line, area, pie, etc
dataPoints: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
}]
});
chart.render();
}
</script>
HTML
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
2nd php code for pie chart
<?php
$dataPoints = array();
//Best practice is to create a separate file for handling connection to database
try{
// Creating a new connection.
// Replace your-hostname, your-db, your-username, your-password according to your database
$link = new \PDO( 'mysql:host=localhost;dbname=OISC;charset=utf8mb4', //'mysql:host=localhost;dbname=canvasjs_db;charset=utf8mb4',
'root', //'root',
'', //'',
array(
\PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_PERSISTENT => false
)
);
$handle = $link->prepare("SELECT BasedAt, COUNT(BasedAT) as TotalImmigrant FROM register GROUP By BasedAt");
$handle->execute();
$result1 = $handle->fetchAll(\PDO::FETCH_OBJ);
foreach($result1 as $row){
array_push($dataPoints, array("x"=> $row->BasedAt, "y"=> $row->TotalImmigrant));
}
$link = null;
}
catch(\PDOException $ex){
print($ex->getMessage());
}
?>
2nd JS for pie chart
<script>
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer1", {
animationEnabled: true,
exportEnabled: true,
theme: "light1", // "light1", "light2", "dark1", "dark2"
title:{
text: "Location Pie Chart"
},
data: [{
type: "pie", //change type to bar, line, area, pie, etc
dataPoints: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
}]
});
chart.render();
}
</script>
HTML
<div id="chartContainer1" style="height: 370px; width: 100%;"></div> <!--Location Chart-->
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
Keep first chart as it is and try use this for second chart
window.onload = function () {
var chart_sec = new CanvasJS.Chart("chartContainer1", {
animationEnabled: true,
exportEnabled: true,
theme: "light1", // "light1", "light2", "dark1", "dark2"
title:{
text: "Location Pie Chart"
},
data: [{
type: "pie", //change type to bar, line, area, pie, etc
dataPoints: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
}]
});
chart_sec.render();
}
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>
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);