Currently I pass variables to the api like so:
<script type="text/javascript">
mobileNav();
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// 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 data = new google.visualization.DataTable();
data.addColumn('string', 'Date');
data.addColumn('number', 'Attendance');
data.addRows([
['Present', <?php echo $present; ?>],
['Absent', <?php echo $absent; ?>],
['Directed Study', <?php echo $directed; ?>],
['Medical Certificate', <?php echo $medical; ?>],
['Self Certificate', <?php echo $selfcert; ?>],
['Authorised Absence', <?php echo $authorised; ?>],
]);
// Set chart options
var options = {'title':'Your Attendance'};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
I get the results and everything is good. I would like to access the % values generated by the pie chart. Is there a way this can be achieved?
If you want to access on your values generated by your pie chart , you need to retrieve data on your dataTable().
You need to use getFormattedValue method.
Documentation :
DataTable API : https://developers.google.com/chart/interactive/docs/reference#DataTable
Method : getFormattedValue(rowIndex, columnIndex)
Related
I am trying to output the contents of two arrays as the axis for a chart using Google's chart API.
I currently output the JavaScript function using PHP, which is where I feel the error is. I believe the script is just getting output but not running. I can see it has output in the correct format from the page source, however, no data is being shown on the window.
The following is the contents of my two arrays, which are just key and value pairs in separate arrays:
The following is my code in the HTML body, which I call in PHP in the same page:
<?php
function createChart($nutrientArr, $percentArr) {
$chart = "<script type='text/javascript'>
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.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 data = new google.visualization.DataTable();
data.addColumn('string', 'Nutrient');
data.addColumn('number', 'Percentage Intake');
data.addRows(JSON.parse([";
for($i = 0;$i < count($nutrientArr);$i++) {
$chart .= "['" . $nutrientArr[$i] . "', '" . $percentArr[$i] . "'],";
if($i == count($nutrientArr) - 1) {
$chart .= "['" . $nutrientArr[$i] . "', '" . $percentArr[$i] . "']";
}
}
$chart .= "]));
// Set chart options
var options = {'title':'Daily Nutrient Intake (Percentage)',
'width':500,
'height':400};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>";
echo $chart;
}
?>
This is the source code:
<script type='text/javascript'>
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.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 data = new google.visualization.DataTable();
data.addColumn('string', 'Nutrient');
data.addColumn('number', 'Percentage Intake');
data.addRows(JSON.parse([['Calories', '18.32768'],['Fat', '23.065360824742'],['Saturated Fat', '22.640580645161'],['Monosaturated Fat', '25.274138888889'],['Polyunsaturated Fat', '23.481666666667'],['Carbohydrates', '8.6173573573574'],['Fiber', '17.975466666667'],['Sugar', '13.857878787879'],['Protein', '63.232972972973'],['Cholesterol', '37.102'],['Sodium', '7.8765666666667'],['Calcium', '13.39272'],['Magnesium', '20.481214285714'],['Potassium', '17.816553191489'],['Iron', '52.980375'],['Zinc', '25.689818181818'],['Phosphorus', '51.941142857143'],['Vitamin A', '13.804971428571'],['Vitamin C', '15.494555555556'],['Thiamin (B1)', '21.825333333333'],['Riboflavin (B2)', '23.152538461538'],['Niacin (B3)', '69.055'],['Vitamin B6', '63.236153846154'],['Folate Equivalent (Total)', '40.9758'],['Folate (Food)', '19.098075'],['Folic Acid', '0.8311225'],['Vitamin B12', '24.940875'],['Vitamin D', '2.1734733333333'],['Vitamin E', '13.491866666667'],['Vitamin K', '18.9045']]));
// Set chart options
var options = {'title':'Daily Nutrient Intake (Percentage)',
'width':500,
'height':400};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
I call the createChart() function in PHP at the top of the page, passing the two arrays.
I am looking to see what the best method of passing this data to the chart API is? Should I call the JS function from PHP and pass the arrays that way? I am not too familiar with JS so not sure how I would pass this data. Any help is very appreciated!
I have tried using json_encode and json_parse but neither work as I suspect I'm outputting the code at the wrong time or wrong way.
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
var jsvar = '<?=$count?>';
// Load google charts
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
// Draw the chart and set the chart values
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Rating'],
['Good', <?php echo $count; ?>],
['Average', <?php echo $count1; ?>],
['Bad', <?php echo $count2; ?>],
]);
// Optional; add a title and set the width and height of the chart
var options = {'title':'Windoek' , 'width':400, 'height':400};
// Display the chart inside the <div> element with id="piechart"
var chart = new google.visualization.PieChart(document.getElementById('piechart1'));
chart.draw(data, options);
google.visualization.events.addListener(chart, 'select', function() {
var selection = chart.getSelection();
window.open("table.php?myvar=" + encodeURI(selection));
});
I would like to get the selected task header and send it to new page ......
Example , If someone clicks the bad pie chart slice , The variable Bad and Title of pie chart should be send via link to new page for processing ....if someone selects Good than the variable Good with title of pie chart send to new page
How can I set the intervals on Google Charts?
I don't know if that's how it's called, but, in the image, they are the 200k, 400k and so on.
Since some of my values are pretty small, I need to create intervals at each 5k or so.
How can I set this using Google Charts?
The code I'm using is down here:
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart4);
function drawChart4() {
var data = google.visualization.arrayToDataTable([
<?php echo $dados; ?>
]);
var options = {
chart: {title: <?php echo "'".str_replace('_', ' ', $subtitulo)."'" ?>,
},bars: 'horizontal',
width: 1250,
height: 350,
colors: ['#4c4c4c','#07bb27']
};
var chart = new google.charts.Bar(document.getElementById('column_horizontal'));
chart.draw(data, google.charts.Bar.convertOptions(options));
}
The Google API Chart doesn't take in the value I echo using php can anyone enlighten me to what I'm doing wrong?
This is where the user picks the job chart they want to view:
<form class="form-horizontal form-select-chart" method="post" action="analytics.php">
<select name="chartname">
<?php
$sel_user = "select * from tbl_jobs";
$run_user = mysqli_query($con, $sel_user);
while($row = mysqli_fetch_assoc($run_user))
{
echo "<option value=\"" . $row['Job_ID'] . "\">" . $row['Job_Name'] . "</option>";
}
?>
</select>
<br>
<input type="submit" name="make_chart" value="Create the Chart" class="btn btn-primary" />
</form>
Here is where the data should be processed:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
<?php
if(isset($_POST['make_chart'])){
$jid = mysqli_real_escape_string($con,$_POST['chartname']);
$sel_user = "select * from tbl_jobs WHERE `ID` = '$jid'";
$run_user = mysqli_query($con, $sel_user);
while($row = mysqli_fetch_assoc($run_user))
{
$jname = $row['Job_Name'];
$overall_vacant = $row['Vacant'];
$overall_filled = $row['Filled'];
}
settype($overall_vacant, "integer");
settype($overall_filled, "integer");
}
?>
// Load the Visualization API and the corechart package.
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.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 data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
['Vacant Positions', <?php echo $overall_vacant; ?>],
['Filled Positions', <?php echo $overall_filled; ?>],
]);
// Set chart options
var options = {'title':'<?php echo $jname; ?>',
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
Here is where the data to be displayed:
<?php
if(isset($_POST['make_chart'])){
echo"<div align=\"center\" id=\"chart_div\"></div>";
}
unset($_POST['make_chart']));
?>
Upon further investigation I've found out there's something wrong in my MySQL Query! I should've put "Job_ID" instead of "ID" which are two separate things!
My table goes like this:
ID | Job_ID | Job_Name | Vacant | Filled
1 0 Overall 0 0
Which in turn resulted to a blank chart! How dumb of me! Thanks to MECU for the heads up!
I'd like to retrieve data from database (mongodb) and with those data i'd like to draw à pie chart using google charts. in a first case i have a collection called user and each user has a boolean attribute called (paid), i'd like to count how many paid users and free users and basing on those results i will draw a pie chart with the percentage of each kind of users
this my try i tried with for a long time but i'dont arrive to show the chart,
thanks :)
<?php
$connection = new MongoClient();
$collection = $connection->pato->user;
$cursor = $collection->find();
$cursor = $collection->find(array("paid"=>true));
$x=$cursor->count();
$cursor = $collection->find(array("paid"=>false));
$y=$cursor->count();
$myurl[]="['Option','Value']";
$myurl[]=[['Free users', $y],['Paid users', $x]];
?>
<html>
<head>
<!--Load the AJAX API-->
<body>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
</head>
<script type="text/javascript">
google.load('visualization', '1', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart()
{
var data=google.visualization.arrayToDataTable([
<?echo(implode(",",$myurl));?>
]);
// Set chart options
var options = {'title':'User statistics',
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
chart = new google.visualization.PieChart(document.getElementById('userStatsDiv'));
google.visualization.events.addListener(chart, 'select', selectHandler);
chart.draw(data, options);
}</script>
<body>
<div id="usageStatsDiv" style="width:700; height:500"></div>
</body>
</html>
I think your problem is with your JSON:
var data=google.visualization.arrayToDataTable([
<?echo(implode(",",$myurl));?>
]);
It looks like you're trying to build the JSON string yourself. Let PHP do the work for you instead - use json_encode instead, like this:
var data=google.visualization.arrayToDataTable([
<?php echo json_encode($data); ?>
]);
You'll need to build your $data array so that it gives you the correct elements, but I think you'll find that the end result is cleaner and easier to understand.