i have following code to display pie chart.
<script>
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
//google.charts.setOnLoadCallback(drawChartTwo);
//google.charts.setOnLoadCallback(drawChartThree);
// 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 = google.visualization.arrayToDataTable([
['Type', 'Duration'],
<?php
foreach($val as $data){
echo "['".$data['type']."', ".$data['duration']."],";
}
?>
]);
// Set chart options
var options = {'title':'Duration Analysis',
'width':830,
'height':300,
'is3D': true,
pieSliceText : 'none',
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
</script>
and its working fine. but, now when i see chart on my browser i see it like.
in the image i see list of values in pagination with 3 page. but i want it to display right side of my chart without pagination. any possibility to display 3 colomns instead of 3 pagination page??? Please help me.
Related
I want to introduce my counts into this GoogleChart. I want to count all id from table News/Opinions/Events etc.I want to be able to put numbers of all records from News/Opinions/Events etc. If in "News" table I have 10 news, i want to count them and introduce it to ['News', 'All news HERE'],
And the second, I want to add it into this code:
<script>
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['News', 'All news HERE'],
['Events', No of events from db],
]);
var options = {
title: 'My Daily Activities',
pieHole: 0.4,
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
</script>
You can just query your database to get all counts that you needed (should be fast if you don't query many tables).
public function myControllerAction() {
$dbData = DB::selectOne('
select
(select count(*) from news) as News,
(select count(*) from events) as Events,
(select count(*) from someothertable) as Someotherdata
');
return view('my-view', compact('dbData'));
}
After this you can use $dbData->News, $dbData->Events, $dbData->Someotherdata and put it anywhere you like in your code.
You can even simplify your future development by using Laravel's Collection and generating a ready to use array for google charts:
public function myControllerAction() {
$dbData = DB::selectOne('
select
(select count(*) from news) as News,
(select count(*) from events) as Events,
(select count(*) from someothertable) as Someotherdata
');
$collection = new \Illuminate\Support\Collection($dbData);
$data = $collection->flatMap(function($value, $key) {
// We will use name of the key as the label for chart (News, Events, Someotherdata)
return [[$key, $value]];
})->toArray();
return view('my-view', compact('data'));
}
And just use Blade's #json directive to render the json where you need it:
<script>
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
// Here is the changed part, notice the #json($data) here
var data = google.visualization.arrayToDataTable(#json($data));
var options = {
title: 'My Daily Activities',
pieHole: 0.4,
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
</script>
I really can't fully understand what you are trying to do but I will show you whole concept
in web.php route file :
Route::get('/newsCount', 'NewsController#count');
in NewsController.php controller file :
public function count()
{
$CountOfNews = News::all()->count(); // Get count of all your news
// Now you can use one of these two ways
// Pass data to view way 1
return View::make("user/NewsCount", compact('CountOfNews'));
// Pass data to view way 2
return View::make("user/NewsCount")->with(array('Count'=>$CountOfNews));
}
and into your balde.php view file you should do like this :
<script>
alert({{$CountOfNews}});
</script>
**
I used Google Pie chart using PHP MySQL. If I put my mouse on the
chart it only shows 2 column data from the row. But there are three
columns in that table & I want to show all the columns from the row. I
have written this code to show 3rd column but it doesn't work.
**
var data = google.visualization.arrayToDataTable([
['Problems', 'Sufferer', 'Solutions'],
<?php
while($row = $res->fetch_assoc()){
echo "['".$row['Problems']."',".$row['sum(Sufferer)'].", '".$row['Solutions']."'],";
}
?>
]);
How can I solve this problem? picture of my Pie Chart output example
Google Pie chart only supports 2 columns refer Google Pie Chart
The first one is the slice label and the second one is the slice value.
If you wish to add more information to your chart, you can make use of the tooltip which is displayed on hover.
For more information on columns and roles, refer Column Roles
By default only the slice label and slice value with percentage will be shown in the tooltip of the chart.
This can be customized by passing data in the below format
Data format
var data = google.visualization.arrayToDataTable([
['Pizza', 'Popularity', {type:'string', role:'tooltip'}],
['Pepperoni', 33, "Most popular"],
]);
If you wish to customize the rendering of the tooltip, it can be achieved by passing HTML data as the content of the tooltip.
For more information on tooltips and customizing HTML content, refer Tooltips
Example
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Pizza', 'Popularity', {type:'string', role:'tooltip'}],
['Pepperoni', 33, "Most popular"],
['Hawaiian', 26, "Popular"],
['Mushroom', 22, "Somewhat popular"],
['Sausage', 10, "Less popular"]
]);
var options = {
title: 'Pizza Popularity'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="piechart" style="width: 900px; height: 500px;"></div>
I recently added zoom-in and pan functionality to my line chart. Now i want to add a reset button or something like that when pressed graph come back to normal position/shape. Currently i am drawing it for dynamic data which get updated every10 seconds.
ThankYou in advance.
Try chartjs-plugin-zoom
First, get the Chart.js instance, and then you can just call the resetZoom function of the instance to reset the zooming and panning.
window.myLine = new Chart(ctx, config);
...
function resetZoom() {
window.myLine.resetZoom();
}
...
<button onclick="resetZoom()">Reset Zoom</button>
The chart.js version I'm using is 2.9.3 and chartjs-plugin-zoom version 0.7.7
See examples:
chartjs-plugin-zoom samples
chartjs zoom and pan on codepen
There are multiple ways to do this:
Try any of these:
1. .clear()
2. .destroy()
myLineChart.destroy();
Then re-initialize the chart:
var ctx = document.getElementById("myChartLine").getContext("2d");
myLineChart = new Chart(ctx).Line(data, options);
delete the element and then reappending a new to the parent container
var resetCanvas = function () {
$('#results-graph').remove(); // this is my <canvas> element
$('#graph-container').append('<canvas id="results-graph"><canvas>');
canvas = document.querySelector('#results-graph');
ctx = canvas.getContext('2d');
ctx.canvas.width = $('#graph').width(); // resize to parent width
ctx.canvas.height = $('#graph').height(); // resize to parent height
var x = canvas.width/2;
var y = canvas.height/2;
ctx.font = '10pt Verdana';
ctx.textAlign = 'center';
ctx.fillText('This text is centered on the canvas', x, y);
};`
.update( )
Calling update() on your Chart instance will re-render the chart with any updated values, allowing you to edit the value of multiple existing points, then render those in one animated render loop.
Also refer:
How to clear a chart from a canvas so that hover events cannot be triggered?
chart.js load totally new data
I have a table that looks like the following:
sub_note | item_amount | sub_cat |
---------------------------------------|
Spotify | $5.99 | entertainment |
Vodafone | $35 | phone |
Netflix | $5.99 | entertainment |
I want to display a Google pie chart that tells me how much is being spent per category i.e. Entertainment, Phone etc.
I have used the following adaptation of the Google Quick Start example, but all I'm seeing is a blank chart with 'No data'.
<script type="text/javascript">
// 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', 'Category');
data.addColumn('number', 'Total');
data.addRows([
<?php
$query = "SELECT SUM(sub_amount) AS sub_cat, subs_total FROM subscriptions WHERE sub_user_id ='".$user_id."' GROUP BY sub_cat ORDER BY sub_cat";
$exec = mysqli_query($connect,$query);
while($row = mysqli_fetch_array($exec)){
echo "['".$row['sub_cat']."',".$row['subs_total']."],";
}
?>]);
// Set chart options
var options = {'title':'Spending by Category',
'width':600,
'height':400};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
It's clear that there's something wrong with the query code and how it's being grouped, but I'm scratching my head trying to figure this out.
Any pointers would be great!
UPDATE: Thanks to #WhiteHat for the SQL correction, here's the functioning code:
<script type="text/javascript">
// 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', 'Category');
data.addColumn('number', 'Total');
data.addRows([
<?php
$query = "SELECT sub_cat, SUM(sub_amount) as subs_total FROM subscriptions WHERE sub_user_id ='".$user_id."' GROUP BY sub_cat ORDER BY sub_cat";
$exec = mysqli_query($connect,$query);
while($row = mysqli_fetch_array($exec)){
echo "['".$row['sub_cat']."',".$row['subs_total']."],";
}
?>]);
// Set chart options
var options = {'title':'How Much Pizza I Ate Last Night',
'width':600,
'height':400};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
try this sql...
$query = "SELECT sub_cat, SUM(sub_amount) as subs_total FROM subscriptions WHERE sub_user_id ='".$user_id."' GROUP BY sub_cat ORDER BY sub_cat";
The category should be the first column and subtotal second.
Please can you test if your sql code return something?
I would help you if you give to me the correct dataset in your SQL.
Try to do an echo or vardump outside your javascript to know if your SQL is Good.
I want to create pdf files of pie charts and graphs which are dynamically generated using javascript.
I am using pdfdom for creating the pdf files using php.
But the Problem is that pdfdom is unable to create pdf of the data stored in the javascript here is the sample of my HTML file..
<html>
<head>
<!--Load the AJAX API-->
<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.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', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
['Mushrooms', 3],
['Onions', 1],
['Olives', 1],
['Zucchini', 1],
['Pepperoni', 2]
]);
// Set chart options
var options = {'title':'How Much Pizza I Ate Last Night',
'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>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
Is there any other way to do it please help..its urgent..!!
Alternative:have you tried pchart http://pchart.sourceforge.net/ ? You can use jquery to generate the chart. You can access the script via AJAX(generating the image and making the PDF) and and the response of that script you can get the link of the PDF file.