I create a pie chart using google services. the problem is that i want to show credit and debit in pie chart, but output comes only in one color. Here is my query.
$data = mysqli_query($link, "select SUM(pay_payable) as debit, SUM(pay_paid) as credit from purchasers_payment where p_id = '$pur_id'");
and here is my chart setting.
var data = google.visualization.arrayToDataTable([
['Debit', 'Credit'],
<?php
while($row = mysqli_fetch_array($data))
{
echo "['".$row['debit']."',".$row['credit']."],";
}
?>
]);
var options = {
is3D: true,
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
here is mine code output
enter image description here
and i want output like this:
enter image description here
the data format for a PieChart uses rows for each slice
to get two slices, you need two rows of data...
['Label', 'Value'],
['Debit', 10000],
['Credit', 2000]
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
['Debit', 10000],
['Credit', 2000]
]);
var options = {
is3D: true,
height: 300
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="piechart"></div>
try the following php...
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
<?php
while($row = mysqli_fetch_array($data))
{
echo "['Debit',".$row['debit']."],['Credit',".$row['credit']."],";
}
?>
]);
Related
How can i change color of bar "BLACK"? Now its green
function drawChart() {
var data = google.visualization.arrayToDataTable([
['MODEL', 'CYAN', 'MAGENTA', 'YELLOW', 'BLACK'],
<?php
while($row = mysqli_fetch_array($exec))
{
echo"['$row[1] - $row[0]', $row[5], $row[4], $row[3], $row[2]],";
}
?>
]);
var options = {
chart: {
title: "Stan tonerów z <?php echo $date ?>",
titleTextStyle:{fontSize:76,},
subtitle: ''
},
bars: 'horizontal' // Required for Material Bar Charts.
};
i tried {role: 'style'} but it dosent work
try the config option for: colors
var options = {
chart: {
title: "Stan tonerów z <?php echo $date ?>",
titleTextStyle:{fontSize:76,},
subtitle: ''
},
colors: ['CYAN', 'MAGENTA', 'YELLOW', 'BLACK'],
bars: 'horizontal' // Required for Material Bar Charts.
};
I need to put the values inside the bar or outside it but I need you to show me the value, I've already seen some examples but the arrays tables have more than one line with the values placed in the hand, but mine connects by SQL
How can I place the values on my bar chart?
A user showed me this answer, but in "var data = google.visualization.arrayToDataTable"
It returns the values in the rows
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Descr', 'Downlink', 'Uplink'],
['win7protemplate', 12, 5],
['S60', 14, 5],
['iPad', 3.5, 12], ]);
http://jsfiddle.net/heennkkee/rekso9t6/
But mine only has 1 line per account that pull this value from MySQL
google.load("visualization", "1", {packages:["barchart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['quantidade_demanda','COUNT(Subclasse)'],
<?php
$query = "SELECT COUNT(Subclasse), Subclasse AS quantidade_demanda FROM demandas_portal WHERE Categoria = 'Demanda Ambiental' GROUP BY Subclasse";
$exec = mysqli_query($con,$query);
while($row = mysqli_fetch_array($exec)){
echo "['".$row['quantidade_demanda']."',".$row['COUNT(Subclasse)']."],";
}
?>
]);
Would I have to add a new variable? because I only have these options
var options = {
colors: ['#00544d'],
width: 500,
height: 250
};
options.legend = 'none';
var chart = new google.visualization.BarChart(document.getElementById('chart_demanda'));
chart.draw(data,options);
}
if you are referring to displaying annotations on the bars,
you need to add another column to the data table,
using an annotation role...
add the annotation role to the column heading, here...
['quantidade_demanda','COUNT(Subclasse)', {role: 'annotation', type: 'string'}], // <-- add annoation role to column heading
then repeat the column value as a string, here...
echo "['".$row['quantidade_demanda']."',".$row['COUNT(Subclasse)'].",'".$row['COUNT(Subclasse)']."'],"; // <-- add value of annotation, repeat column value as string
see following snippet...
var data = google.visualization.arrayToDataTable([
['quantidade_demanda','COUNT(Subclasse)', {role: 'annotation', type: 'string'}], // <-- add annoation role to column heading
<?php
$query = "SELECT COUNT(Subclasse), Subclasse AS quantidade_demanda FROM demandas_portal WHERE Categoria = 'Demanda Ambiental' GROUP BY Subclasse";
$exec = mysqli_query($con,$query);
while($row = mysqli_fetch_array($exec)){
echo "['".$row['quantidade_demanda']."',".$row['COUNT(Subclasse)'].",'".$row['COUNT(Subclasse)']."'],"; // <-- add value of annotation, repeat column value as string
}
?>
]);
currently I am trying to show 3 Google Charts on a page, but the page is blank, it does not display any of the charts. Originally the 1st chart was displayed, then it worked but ever since I attached the 2nd one (even if I deleted that so only the 1st one would be shown again), the page I have is totally blank and I don't know why.
Could you please help me?
Here is my code (I set the $conn and $_SESSION variables at the top of my page):
EDIT: Here is a picture about the source code in my browser:
[![sourcecode][1]][1] What I don't understand is that it looks like it would expect other values to data1 and data2 and that is why the charts are not displayed...
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dashboard</title>
<link rel="stylesheet" href="styles.css">
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
// Load Charts and the corechart package.
google.load('current', callback: drawCharts, {packages:['column', 'pie']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawCharts);
// Callback that creates and populates a data table, instantiates the pie chart, passes in the data and draws it.
function drawCharts() {
var data1 = google.visualization.arrayToDataTable([
['Classification', 'Number of assets'],
<?php
if ($_SESSION['user_type'] == 'admin') {
$sql = "SELECT Classification, count('Classification') as count FROM `assets` GROUP BY Classification ORDER BY FIELD(Classification, 'high', 'medium', 'low')";
}else{
$sql = "SELECT Classification, count('Classification') as count FROM `assets` WHERE Responsible =".$_SESSION['name']." GROUP BY Classification ORDER BY FIELD(Classification, 'high', 'medium', 'low')";
}
$result = mysqli_query($conn,$sql);
while ($result2=mysqli_fetch_array($result)) {
echo "['".$result2['Classification']."',".$result2['count']."],";
}
?>
]);
var data2 = google.visualization.arrayToDataTable([
['Risks', 'Percentage'],
<?php
if ($_SESSION['user_type'] == 'admin') {
$sql = "SELECT Compliant = (SELECT count('id') FROM `risks` WHERE targetrisk >= residualrisk), Non-compliant = (SELECT count('id') FROM `risks` WHERE targetrisk < residualrisk) FROM risks ";
}else{
$sql = "SELECT Compliant = (SELECT count('id') FROM `risks` WHERE responsible =".$_SESSION['name']." AND targetrisk >= residualrisk), Non-compliant = (SELECT count('id') FROM `risks` WHERE ".$_SESSION['name']." AND targetrisk < residualrisk) FROM risks ";
}
$results = mysqli_query($conn,$sql);
while ($result2=mysqli_fetch_array($results)) {
echo "['".$result2['Compliant']."',".$result2['Non-compliant']."],";
}
?>
]);
var data3 = google.visualization.arrayToDataTable([
['Assets', 'Percentage'],
<?php
if ($_SESSION['user_type'] == 'admin') {
$sql = "SELECT count('Asset_name') as Assets, count(`risks`.`assettag`) as Compliant assets FROM `assets`, `risks` JOIN `assettag` ON `assets`.`Tag` = `risks`.`assettag` ";
}else{
$sql = "SELECT count('Asset_name') as Assets, count(`risks`.`assettag`) as Compliant assets FROM `assets`, `risks` JOIN `assettag` ON `assets`.`Tag` = `risks`.`assettag` AND responsible =".$_SESSION['name']."";
}
$results = mysqli_query($conn,$sql);
while ($result2=mysqli_fetch_array($results)) {
echo "['".$result2['Assets']."',".$result2['Compliant assets']."],";
}
?>
]);
var options1 = {
title: 'Asset classification',
legend: { position: 'none' },
width: 900,
height: 500
};
var options2 = {
title: 'Risk compliance',
legend: { position: 'none' },
width: 900,
height: 500
};
var options3 = {
title: 'Asset compliance',
legend: { position: 'none' },
width: 900,
height: 500
};
var chart1 = new google.visualization.ColumnChart(document.getElementById("columnchart"));
chart1.draw(data1, options1);
var chart2 = new google.visualization.PieChart(document.getElementById("piechart"));
chart2.draw(data2, options2);
var chart3 = new google.visualization.PieChart(document.getElementById("piechart2"));
chart3.draw(data3, options3);
}
</script>
</head>
<body>
<div id="columnchart"></div>
<br>
<div id="piechart" ></div>
<br>
<div id="piechart2" ></div>
</body>
</html>
[1]: https://i.stack.imgur.com/f2u3D.png
I am using the code below to generate a line chart for a projected financial balance. Data is generated from information in a MySQL database. What I would like to be able to do is to have a form with an input field on the page that allows the user to set the starting balance dynamically once the page is loaded, such that the chart is redrawn with the correct starting balance, but I can't work out how to do this:
$rows = array();
$table = array();
$table['cols'] = array(
array('label' => 'Date', 'type' => 'string'),
array('label' => 'Amount', 'type' => 'number')
);
[code to generate data goes here - i.e. calculating a balance for each date in the chart]
$balance = $balance - $monthly - $weekly + $session_total;
$temp = array();
$temp[] = array('v' => (string) $date_display);
$temp[] = array('v' => (string) $balance);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
//echo $jsonTable;
?>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
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 formatter = new google.visualization.NumberFormat({fractionDigits:2,prefix:'\u00A3'});
formatter.format(data, 1);
var options = {
pointSize: 5,
legend: 'none',
hAxis: { showTextEvery:31 },
series: {0:{color:'2E838F',lineWidth:2}},
chartArea: {left:50,width:"95%",height:"80%"},
backgroundColor: '#F7FBFC',
height: 400
};
// Instantiate and draw our chart, passing in some options.
//do not forget to check ur div ID
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<div id="chart_div"></div>
Hopefully there's a fairly simple way to refresh the chart when new data is available. It requires a small change to your PHP and a few JavaScript tweaks.
The nice thing about using Google Charts is that you can just re-draw them by calling drawChart() again, you just need to be able to modify the data before you do it.
The change I would make the PHP would be to store the original value, so that when you want to change the value according to the user's input you can always have something to refer back to:
// display the date
$temp[] = array('v' => (string) $date_display);
// the data used by the chart
$temp[] = array('v' => (string) $balance);
// the original value
$temp[] = array('v' => (string) $balance);
I would also make the table data global rather than drawing it directly into the function, this way you can change it and refresh the chart quite easily.
var table = <?php echo $jsonTable; ?>;
function drawChart() {
var data = new google.visualization.DataTable(table);
......
}
I tested this with a basic form that looks like this:
<form method="post" action="#" onsubmit="return false;">
<input type="text" id="balance1" />
<input type="text" id="balance2" />
<button onclick="return refreshChart()">Go</button>
</form>
Clicking on the button cancels the default action and calls a function called refreshChart(). This function takes the value and adds it to the original values on the fly before re-drawing the chart:
function refreshChart() {
var balance1 = document.getElementById('balance1').value;
var balance2 = document.getElementById('balance2').value;
if(!balance1) {
balance1 = 0;
}
if(!balance2) {
balance2 = 0;
}
for(var i = 0, length = table.rows.length; i < length; i++) {
table.rows[i].c['1'].v = parseFloat(table.rows[i].c['2'].v) + parseFloat(balance1) + parseFloat(balance2);
}
drawChart();
return false;
}
It takes the balance entered and adds it to the original value stored in table.rows[i].c['2'].v and overwrites the value in table.rows[i].c['1'].v which is used by the chart. It then calls the original drawChart() function but the new data is used.
I played around with some default data and this is the output I tested it with on JSFiddle.
Hello I want to have a % in my google chart data i have my data like a number but is not accepting % symbol.
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Year');
data.addColumn('number', 'Sales');
data.addRows([
['Line 1', 71.36, 71.36871],
['line 2', 3.07, 74.44134]
]);
var options = {
width: 400, height: 240,
title: 'Company Performance'
};
var chart = new
google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, {vAxis: {format:'#,#%'} } );
}
I tried puting the data like
['Line 1', 71.36,'71.36%'],
['line 2', 3.07,'3.07%' ]
]);
Google charts accepts as to give a dictionary with two elements "v" from value and "f" from format.
You can give your values as
data.addRows([
['Line 1', {"v":71.36871,"f":"71.36%"}],
['line 2', {"v":3.07,"f":"3.07%"}]
]);