I am using a Google Pie Chart in my website to show some data of company expenses. The chart gives me nice tooltips as I hover over the slices. It says for example 27% and gives the number of expense as 522552225.00 for example. What I would like to do is to get the number formatted as it is hard to read when the number is large. I would like to have this instead 522,552,225.00.
The problem is that the number comes from database.
Is there a solution to this?
Thanks!
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
["Label","Value"],
<?php echo $MyDataArrayAsString; ?>
]);
var formatter = new google.visualization.NumberFormat({pattern:'#,###.00'});
// format column 1 of DataTable "data"
formatter.format(data, 2);
var options = {"width":<?php echo $params->get('width')?>,
"height":<?php echo $params->get('height')?>,
"tooltip": {"trigger": '<?php echo $params->get('tooltip')?>' },
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
</script>
Use a NumberFormatter on the appropriate DataTable column:
var formatter = new google.visualization.NumberFormat({pattern: '#,###.00'});
// format column 1 of DataTable "data"
formatter.format(data, 1);
Related
I want to insert data to get sales report from two table into google chart. I have tried join query in model page, but the result is No Data in pie chart div.
Data from table sales is like below
id | person_name | sales_id | status
1 Michael 2 1
2 Daniel 2 3
3 James 2 1
4 Ricky 1 2
5 Martin 1 3
The data from table status is like below
id | status | color
1 Meeting #f00630
2 Presentation #f2478f
3 Proposal Sent #170303
4 Invoice #7cb342
5 Lost #fe0725
I need to insert data status type, total status (in number), and color status into google pie chart based on sales id. I need to change data which I write manually like below
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Type', 'Total'],
['Meeting', 2],
['Presentation', 0],
['Proposal Sent', 1],
['Invoice', 0],
['Lost', 0]
]);
var options = {
is3D: true,
colors: ['#f00630', '#f2478f', '#170303', '#7cb342', '#fe0725']
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
Here is the script I have tried in model page
public function getAllStatus()
{
$this->db->select('status');
$this->db->from('sales');
$this->db->join('sales_status', 'sales_status.id = sales.status');
$this->db->where('sales_id', $id);
return $query = $this->db->get();
}
Here's script in controller page
$data['sales'] = $this->Sales_model->getAllStatus()->result();
And here's the script in view page
var data = google.visualization.arrayToDataTable([
['Type', 'Total'],
<?php
foreach ($sales as $sale){
echo "['".$sale->name."',".$sale->count."],";
}
?>
]);
<div id="chart_div" style="width: 100%; "></div>
Do you know where's I need to fix ?
Thank you
The chart expects JSON objects with the data. You can try to build JSON-like structures with loops like you did, but it's much simpler to just output the JSON objects.
In your view, before the call to the chart is made:
var first_data = <?php echo json_encode($your_first_var); ?>;
var second_data = <?php echo json_encode($your_second_var); ?>;
then, when you actually invoke the JS that will draw the chart:
function drawChart() {
var data = google.visualization.arrayToDataTable(first_data);
var options = {
is3D: true,
colors: second_data
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
I have a table Trailers which contain trailers and the number of views of a trailer.Here i passed data from table Trailers to view using ViewBag and i want to draw a google chart using this data in viewbag but i have no idea about how to convert datas in viewbag to array required to draw chart in javascript
Here is the code used in javascript
<script type="text/javascript">
google.charts.load("current", { packages: ["corechart"] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Views per Day'],
#foreach(var t in ViewBag.trailer)
{
[t.mov_name, t.count],
}
]);
var options = {
title: 'My Daily Activities',
pieHole: 0.4,
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
</script>
I don'know how to insert datas in ViewBag to the variable data.
Please help me
You can do it like below
var trailers = #Html.Raw(ViewBag.trailer);
var data = google.visualization.arrayToDataTable(['Task', 'Views per Day'], trailers);
May be you need to properly manipulate trailer object before passing it to parameter.
Html.Raw() will resolve your issue.
I am trying to draw a Motion Chart using Fusion table API. The error message I am receiving is
Could not parse query.
I had my fusion table format to be text on first column, date on second column, as required by the visualization type. This is my code, underneath. What am I doing wrong?
<script type="text/javascript">
google.load("visualization", "1", {packages:["motionchart"]});
google.setOnLoadCallback(drawVisualization);
function drawVisualization() {
google.visualization.drawChart({
"containerId": "scatter",
"dataSourceUrl": "//www.google.com/fusiontables/gvizdata?tq=",
"query": "SELECT 'Nationality','Date','StatusofStudentship','Gender','ModeofAdmission','CourseofStudy','ProgrammeofStudy','CGPA','Race','EnglishLanguageProficiency','Disability','ModeofStudy','InternshipLength','SoftskillQuality','HealthSoundness','Employability','DefermentLength','Religion','Mode of Sponsorship',FROM " + "19mRBx3ysm3VfJQ746j8obWldgjxpw1-sBNdQy4kQ#rows:id=1",
"refreshInterval": 20,
"chartType": "MotionChart",
"options": {}
});
options['state'] =
chart.draw(data, {width: 900, height:400});
'{"colorOption":"4","iconKeySettings":[],"nonSelectedAlpha":0.4,"orderedByX":false,"iconType":"BUBBLE","yAxisOption":"3","uniColorForNonSelected":false,"yZoomedDataMin":150,"dimensions":{"iconDimensions":["dim0"]},"orderedByY":false,"xZoomedIn":false,"yZoomedDataMax":617,"duration":{"multiplier":1,"timeUnit":"D"},"showTrails":true,"xAxisOption":"2","xZoomedDataMax":1200,"time":"1988","xZoomedDataMin":300,"playDuration":15000,"yLambda":1,"sizeOption":"_UNISIZE","yZoomedIn":false,"xLambda":1};';
options['width'] = 900;
options['height'] = 400;
}
google.setOnLoadCallback(drawVisualization);
</script>
Please help! I am about to go insane over this! I have a Javascript for Google Chart that builds a table and a chart on the same dataset and when you sort the table the values on the chart get sorted as well. I also have a code that opens up the Google Charts Editor... which builds it's own chart. What I need is to merge these two functions. I need to build a table and a chart (that will get sorted as I sort the table) and when I open the Editor I need it to edit THAT chart (which will still be linked with sorting in the table) and NOT build a NEW chart.
Here are the 2 functions I have:
function drawSort() {
var data = new google.visualization.DataTable( <?= $jsonTable ?> );
var formatter = new google.visualization.NumberFormat({
prefix: '$'
});
formatter.format(data, 1); // Apply formatter to second column
var view = new google.visualization.DataView(data);
view.setColumns([0, 1]);
var table = new google.visualization.Table(document.getElementById('table_s_div'));
table.draw(view);
var chart = new google.visualization.BarChart(document.getElementById('chart_s_div'));
chart.draw(view);
google.visualization.events.addListener(table, 'sort',
function (event) {
data.sort([{
column: event.column,
desc: !event.ascending
}]);
chart.draw(view);
});
}
var chartEditor = null;
function loadEditor() {
// Create the chart to edit.
var data = new google.visualization.DataTable( <?= $jsonTable ?> );
var wrapper = new google.visualization.ChartWrapper({
chartType: 'LineChart',
dataTable: data,
options: {
'title': 'Number of Newly Opened Roles per <?echo $_SESSION['
Display ']?>',
'legend': 'none',
}
});
chartEditor = new google.visualization.ChartEditor();
google.visualization.events.addListener(chartEditor, 'ok', redrawChart);
chartEditor.openDialog(wrapper, {})
}
// On "OK" save the chart to a <div> on the page.
function redrawChart() {
chartEditor.getChartWrapper().draw(document.getElementById('chart_s_div'));
}
I have an array in my PHP code (budgetingMain.php) called "totals". I want to use it for my data to create a Google Pie Chart. However, I am having difficulty in encoding it.
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
var jsontotals = <?php echo json_encode($totals) ?>;
// 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', 'Category');
data.addColumn('number', 'Amount Spent on it');
data.addRows([
'jsontotals'
]);
// 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('chartcontainer'));
chart.draw(data, options);
}
</script>
In this current setup, I get the following error: "Uncaught SyntaxError: Unexpected token <" for this line.
var jsontotals = <?php echo json_encode($totals) ?>;
I realise it's an issue with the embedding, but I cannot find a way to get it to work. Any help welcome!
EDIT: This is the structure of totals
$totals = array(
array("ClothingAndAccessories",0),
array("FlowersAndDecorations",0),
array("Ceremony",0),
array("Reception",0),
array("Photography",0),
array("Gifts/favours",0),
array("Stationary",0),
array("Entertainment",0),
array("Other",0)
);