Drawing Google pie by dynamic data - javascript

I am trying to draw a simple Google pie chart by creating a dynamic table using JavaScript.
Why my code fails?
var g;
for (g=0; g <3; g++) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Task');
data.addColumn('number', 'Failed');
data.addColumn('number', 'Passed');
data.addRows(1);
data.setCell(0, 0, "Work?");
data.setCell(0, 1, 80);
data.setCell(0, 2, 20);
var chartName = 'piechart'+(g+1);
var chart = new google.visualization.PieChart(document.getElementById(chartName));
chart.draw(data,options);
}
3 pie charts are being drawn on my screen, but they all have one color and one slice, and not 20% 80% like in my code.
Also, I'm not getting any errors on my console.

Are you aiming for something like this?
Also if you can, consider using addRows instead of setCell
I think the problem is with your table / data structure.
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="piechart1"></div>
<div id="piechart2"></div>
<div id="piechart3"></div>
<script>
// 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);
function drawChart() {
var g;
for (g = 0; g < 3; g++) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'PassOrfail');
data.addColumn('number', 'Percentage');
data.addRows([
['Passed', 80],
['Failed', 20],
]);
var chartName = 'piechart' + (g + 1);
var chart = new google.visualization.PieChart(document.getElementById(chartName));
chart.draw(data);
}
}
</script>

Related

How Can I Tell If I Clicked the Background of a Google Graphs ScatterChart?

I have a google scatterchart that I want to change the color of a point if I click on it, and to reset the points to their original color if I don't click on any point (e.g. if I click on the background).
From what I see on the api, clicking the background should fire a select event that returns a null selection. However, my select handler only ever gets called if I click on a point, not if I click on the graph's background. (I can tell by looking at the console output --- it should print "A" if my handler fires --- as well as the graph.) Clicking anywhere other than on a point doesn't fire the handler at all.
How can I get if I'm clicking on a non-point part of the graph or not?
function makeGraph(row_data, x_axis_title, y_axis_title) {
var data = new google.visualization.DataTable();
data.addColumn('number', x_axis_title);
data.addColumn('number', y_axis_title); // Required to be a number
data.addColumn( {'type': 'string', 'role': 'style'} ); // Defines point style
let pointStyle = 'point { size: 12; shape-type: circle; fill-color: #FFFFFF; color: #CCCCCC }';
let focusedPointStyle = 'point { size: 14; shape-type: circle; fill-color: #B5D989; color: #CCCCCC }';
for (let [index, row_data_i] of Object.entries(row_data)) {
row_data_i[2] = pointStyle;
}
data.addRows(row_data);
var options = {
chart: { title: "myGraph" }
};
var chart = new google.visualization.ScatterChart(document.getElementById(div_id_for_graph));
// SELECT HANDLER
function selectHandler() {
console.log("A");
let selected_graph_item = chart.getSelection()[0];
// Need to reset all points to standard formatting
for (let i = 0; i < row_data.length; i++)
data.setCell(i, 3, pointStyle);
if (selected_graph_item === undefined) { // Didn't click on a point, but on blank graph space
pass;
}
else {
data.setCell(selected_graph_item["row"], 3, focusedPointStyle);
}
chart.draw(data, options); // Redraw so point coloring gets updated
}
// Listen for the 'select' event, and call my function selectHandler() when
// the user selects something on the chart.
google.visualization.events.addListener(chart, 'select', selectHandler);
// DRAW CHART
chart.draw(data, options);
}
the 'select' event is only fired when a point is selected, or un-selected.
to know if the chart background was clicked, use the 'click' event.
the click event will send properties to the event handler specifying the chart element that was clicked.
in this case, we need to ignore click events on points, as these will be handled in the select handler.
we also need to use the 'ready' event, to know when the chart has been re-drawn.
here, we save and set the chart selection, otherwise, a point cannot be un-selected.
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(makeGraph);
function makeGraph(row_data, x_axis_title, y_axis_title) {
var data = new google.visualization.DataTable();
data.addColumn('number', 'x_axis_title');
data.addColumn('number', 'y_axis_title'); // Required to be a number
data.addColumn( {'type': 'string', 'role': 'style'} ); // Defines point style
let pointStyle = 'point { size: 12; shape-type: circle; fill-color: #FFFFFF; color: #CCCCCC }';
let focusedPointStyle = 'point { size: 14; shape-type: circle; fill-color: #B5D989; color: #CCCCCC }';
data.addRows([
[0, 0, pointStyle],
[1, 1, pointStyle],
[2, 2, pointStyle]
]);
var options = {
backgroundColor: '#002855',
title: "myGraph"
};
var chart = new google.visualization.ScatterChart(document.getElementById('chart'));
var selection = [];
// READY HANDLER
function readyHandler() {
if (selection.length > 0) {
chart.setSelection(selection);
}
}
// SELECT HANDLER
function selectHandler() {
// reset all points to standard formatting
for (let i = 0; i < data.getNumberOfRows(); i++) {
data.setCell(i, 2, pointStyle);
}
selection = chart.getSelection();
if (selection.length > 0) {
data.setCell(selection[0].row, 2, focusedPointStyle);
}
chart.draw(data, options); // Redraw so point coloring gets updated
}
// CLICK HANDLER
function clickHandler(sender) {
if (sender.targetID.indexOf('point') === -1) {
// reset all points to standard formatting
for (let i = 0; i < data.getNumberOfRows(); i++) {
data.setCell(i, 2, pointStyle);
}
selection = [];
chart.draw(data, options); // Redraw so point coloring gets updated
}
}
google.visualization.events.addListener(chart, 'ready', readyHandler);
google.visualization.events.addListener(chart, 'click', clickHandler);
google.visualization.events.addListener(chart, 'select', selectHandler);
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart"></div>

Set single point as active / show point and tooltip in Google line chart

Im currently using a Google line chart to show two lines intercepting each other. I would like to show the data point and if possible the tooltip as well, where the lines are intercepting.
My current solution is to show all points and increase the size for the specific point, but actually I want to keep the functionality of seeing the points when pointing on them.
if (!intercept && oldVal > newVal) {
intercept = true
point = 'point { size: 10; }'
}
data.push([i + 1, oldVal, newVal, point])
it looks like you're on the right track with the point size.
we have to set the pointSize config option to something greater than zero,
in order to be able to set the size in our style column.
but we can use something like --> pointSize: 0.1
to prevent the other points from being visible.
as for the tooltip, we can set the tooltip.trigger option to either...
'selection' or 'both'
tooltip: {
trigger: 'both'
}
then we can use the chart's 'ready' event,
to set the chart's selection
google.visualization.events.addListener(chart, 'ready', function () {
chart.setSelection([{row: intercept, column: 2}]);
});
with the above trigger option, when we set the chart's selection,
the tooltip will automatically appear.
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = new google.visualization.DataTable();
data.addColumn('number', 'X');
data.addColumn('number', 'Old');
data.addColumn('number', 'New');
data.addColumn({type: 'string', role: 'style'});
var intercept = null;
var rows = new Array(10);
$.each(rows, function (i) {
var oldVal = i;
var newVal = rows.length - i;
var point = null;
if ((intercept === null) && (oldVal === newVal)) {
intercept = i;
point = 'point { size: 10; }';
}
data.addRow([i + 1, oldVal, newVal, point])
});
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
google.visualization.events.addListener(chart, 'ready', function () {
chart.setSelection([{row: intercept, column: 2}]);
});
chart.draw(data, {
pointSize: 0.1,
tooltip: {
trigger: 'both'
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Google Chart not displaying correctly in Chart Area

Actually, I am facing related to the Google charts while implementing with Dynamic data. Here the issue When ever I am clicking a tab that particular data has to be displayed in Chart.Suppose Say like Clicking the current Day is displaying the below result in chart
After pressing on the tab say after pressing Last week it is not displaying chart correctly in chart area
Suppose if u press again Current Day the char is displayed like this
Here the chart area is not working properly after having first click and second click
`google.charts.load('current', { 'packages': ['bar'] });
$('#t1').click(function () {
google.charts.setOnLoadCallback(BarC);
function BarC() {
var jsonData = $.ajax({
type: 'GET',
url: xxxx.xxxx.xxxx,
dataType: 'json',
}).done(function (results) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'data1');
data.addColumn('number', 'data2');
data.addColumn('number', 'data3');
data.addColumn('number', 'data4');
data.addRows(results.length);
for (i = 0; i < results.length; i++) {
data.setValue(i, 0, results[i]["data1"]);
data.setValue(i, 1, parseInt(results[i]["data2"]));
data.setValue(i, 2, parseInt(results[i]["data3"]));
data.setValue(i, 3, parseInt(results[i]["data4]));
}
var options = {
backgroundColor: 'transparent',
bars: 'vertical',
chartArea: { left: 0, top: 0, width: '100%', height: '100%' }// Required for Material Bar Charts.
};
var chart = new google.charts.Bar(document.getElementById('chart'));
chart.draw(data, google.charts.Bar.convertOptions(options));
}
);
}
});`
Try
google.charts.setOnLoadCallback(function() {
$('#t1').click(function () {
// ...
});
$('#t2').click(function () {
// ...
});
// ...
});
https://embed.plnkr.co/19CellQvdGZTjzf9hikU/

Empty GetSelection() Object in Google Charts' Gantt Chart

I've been learning to use Google Charts for a while and so far, I'm having no problem. However, recently I tried using Gantt Charts and a problem came up. I managed to draw a chart correctly with a data fed by SQL server. However, I want to alert the ID of the selected entity if a chart entity is clicked.
I understand that Google Charts have this getSelection() function and Event Handler. However, when I'm trying to implement that, the array returns empty (just [{}] written in the console). I even used Google Charts' example but it still returns empty array.
Here's the code I use:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script>
google.charts.load('current', {'packages':['gantt']});
google.charts.setOnLoadCallback(drawChart);
function daysToMilliseconds(days) {
return days * 24 * 60 * 60 * 1000;
}
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Task ID');
data.addColumn('string', 'Task Name');
data.addColumn('date', 'Start Date');
data.addColumn('date', 'End Date');
data.addColumn('number', 'Duration');
data.addColumn('number', 'Percent Complete');
data.addColumn('string', 'Dependencies');
data.addRows([
['Research', 'Find sources',
new Date(2015, 0, 1), new Date(2015, 0, 5), null, 100, null],
['Write', 'Write paper',
null, new Date(2015, 0, 9), daysToMilliseconds(3), 25, 'Research,Outline'],
['Cite', 'Create bibliography',
null, new Date(2015, 0, 7), daysToMilliseconds(1), 20, 'Research'],
['Complete', 'Hand in paper',
null, new Date(2015, 0, 10), daysToMilliseconds(1), 0, 'Cite,Write'],
['Outline', 'Outline paper',
null, new Date(2015, 0, 6), daysToMilliseconds(1), 100, 'Research']
]);
var options = {
height: 275
};
var chart = new google.visualization.Gantt(document.getElementById('chart_div'));
// When the table is selected, update the orgchart.
google.visualization.events.addListener(chart, 'select', function()
{
var obj = chart.getSelection();
alert(obj[0].column);
});
chart.draw(data, options);
}
</script>
<div id="chart_div"></div>
Here's the jsfiddle: https://jsfiddle.net/2ku7tzex/1/#&togetherjs=cjVlbdFhV3
Does anybody know where I did wrong?
Thanks before!
This https://jsfiddle.net/hrtgp54r/ resolved the issue for me.
google.visualization.events.addListener(chart, 'select', selectHandler);
function selectHandler(){
var selections = chart.getSelection();
if (selections.length == 0)
{
alert('Nothing selected');
}
else
{
var selection = selections[0];
console.info(selection);
alert('You selected ' + (selection.row == null ? 'something' : data.getValue(selection.row, 0)));
}
};

Google multiple GeoMaps, API

How can I use multiple GeoMaps ?
If I have only one map everything is ok. If I try to add another, without loading again the geomap visualization the map doesn't load, and if I try to load them, I get an error: Uncaught TypeError: Object #<Object> has no method 'Load' The function names are the same for the both map, if I change the functions' names for the second map then I have to change the callback
google.setOnLoadCallback(drawMap);
But, if I do so I get the error posted above....
More code:
//first map
<script type="text/javascript">
google.load("visualization", "1", {"packages": ["geomap"]});
google.setOnLoadCallback(drawMap);
function drawMap() {
var data = new google.visualization.DataTable();
data.addRows(16);
data.addColumn("string", "City");
data.addColumn("number", "Numar anunturi");
data.setValue(1, 0, 'Ilfov');
data.setValue(1, 1, 6);
var options = {width: 800,height:400};
options["region"] = "RO";
options["colors"] = [0xFF8747, 0xFFB581, 0xc06000]; //orange colors
options["dataMode"] = "markers";
var container = document.getElementById("map_chart_div");
var geomap = new google.visualization.GeoMap(container);
geomap.draw(data, options);
}
</script>
//second map
<script type="text/javascript">
function drawMap() {
var data = new google.visualization.DataTable();
data.addRows(16);
data.addColumn("string", "City");
data.addColumn("string", "pret/mp:");
data.setValue(0, 0, 'Ilfov');
data.setValue(0, 1, '50.44');
var options = {width: 800,height:400};
options["region"] = "RO";
options["colors"] = [0xFF8747, 0xFFB581, 0xc06000]; //orange colors
options["dataMode"] = "markers";
var container = document.getElementById("map_pret_div");
var geomap = new google.visualization.GeoMap(container);
geomap.draw(data, options);
}
</script>
I modified your code as follows and it seems to work now, although you have to be patient for the second map to load. I'm listening for the drawingDone event on the first map before firing off the second map. My theory is that this staggering prevents the two maps from stepping on each other's data structures inside of the Visualization API. But even if I'm wrong about the cause, this at least works.
My changes could use some tidying. Sorry about that. I'm in a bit of a rush, but wanted to get the working code to you before I ran off to do other things.
<script type="text/javascript">
google.load("visualization", "1", {"packages": ["geomap"],"callback": "drawMaps"});
function drawMaps() {
drawMap1();
}
function drawMap1() {
var data = new google.visualization.DataTable();
data.addRows(16);
data.addColumn("string", "City");
data.addColumn("number", "Numar anunturi");
data.setValue(1, 0, 'Ilfov');
data.setValue(1, 1, 6);
var options = {width: 800,height:400};
options["region"] = "RO";
options["colors"] = [0xFF8747, 0xFFB581, 0xc06000]; //orange colors
options["dataMode"] = "markers";
var container = document.getElementById("map_chart_div");
var geomap = new google.visualization.GeoMap(container);
geomap.draw(data, options);
google.visualization.events.addListener(geomap, 'drawingDone', drawMap2);
}
function drawMap2() {
var data = new google.visualization.DataTable();
data.addRows(16);
data.addColumn("string", "City");
data.addColumn("string", "pret/mp:");
data.setValue(0, 0, 'Ilfov');
data.setValue(0, 1, '50.44');
var options = {width: 800,height:400};
options["region"] = "RO";
options["colors"] = [0xFF8747, 0xFFB581, 0xc06000]; //orange colors
options["dataMode"] = "markers";
var container = document.getElementById("map_pret_div");
var geomap2 = new google.visualization.GeoMap(container);
geomap2.draw(data, options);
}
</script>

Categories

Resources