Google Chart not displaying correctly in Chart Area - javascript

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/

Related

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>

tricky part of google charts Column with drill down functionality?

i am creating google charts and I already implement top 5 user column charts after that if you select first user column than displaying first user page history data from other variables(eachuser_data) its easy implement function in high charts! but in google charts, I don't know about add events.addListener work or not in this problem. let me know google charts provide click event on each column and display other graphs in same graph draw function. ? thank you in advance
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var charts = {};
var options = {
Column: {
chartArea: {
height: '100%',
width: '100%',
top: 24,
left: 64,
right: 32,
bottom: 48,
},
'vAxis': {
title: 'Cost in USD ($)', format:'$#',
},
height: '100%',
legend: {
position: 'bottom'
},
width: '100%'
}
};
// columns charts data
//top 5 user data with total click
var jsonData = [["johan",69],["jack",23],["scott",24],["x",5],["y",10]];
loadData(jsonData, '1', 'Column');
//specifc user data
var user1 = [["report1",45],["report2",40],["index.html",50]];
var user2 = [["report1",4],["report2",3],["index.html",5]];
var user3 = [["report1",4],["report2",3],["index.html",5]];
var user4 = [["report1",4],["report2",3],["index.html",5]];
var user5 = [["report1",4],["report2",3],["index.html",5]];
// load json data
function loadData(jsonData, id, chartType) {
// create data table
var dataTable = new google.visualization.DataTable();
// add date column
dataTable.addColumn('string', 'Total numbe of click');
var rowIndex = dataTable.addRow();
dataTable.setValue(rowIndex, 0, dataTable.getColumnLabel(0));
$.each(jsonData, function(productIndex, product) {
var colIndex = dataTable.addColumn('number', product[0]);
// add product data
dataTable.setValue(rowIndex, colIndex, product[1]);
});
// draw chart
$(window).resize(function () {
drawChart(id, dataTable);
});
drawChart(id, dataTable);
}
function drawChart(id, dataTable) {
if (!charts.hasOwnProperty(id)) {
charts[id] = new google.visualization.ChartWrapper({
chartType: 'ColumnChart',
containerId: 'chart-' + id,
options: {
vAxis: {
title: 'Cost in USD ($)',
format: '$#',
},
width: '100%',
height: '100%',
legend: {
position: 'bottom'
},
},
});
}
charts[id].setDataTable(dataTable);
charts[id].draw();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart-1"></div>
to know which column has been clicked / selected,
listen for the 'select' event
google.visualization.events.addListener(chart, 'select', chartSelection);
then use chart method getSelection() to get the row and column index of the column selected
getSelection will return an array of objects
[{row: 0, column: 1}]
the select event will fire both when a column is selected and un-selected
be sure to check the length of the array return by getSelection()
before trying to access the array contents
for column charts, only one column can be selected at a time
so the values of the selection will always be the first element in the array
function chartSelection() {
var selection = chart.getSelection();
if (selection.length > 0) {
var row = selection[0].row;
var col = selection[0].column;
var xValue = data.getValue(row, 0);
var yValue = data.getValue(row, col);
console.log('selection: ' + xValue + ' = ' + yValue);
} else {
console.log('nothing selected');
}
}
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['x', 'y0', 'y1'],
['A', 6, 7],
['B', 7, 9],
['C', 8, 11],
['D', 9, 11],
['E', 5, 6]
]);
var options = {
legend: {
alignment: 'end',
position: 'top'
}
};
var container = document.getElementById('chart_div');
var chart = new google.visualization.ColumnChart(container);
google.visualization.events.addListener(chart, 'select', chartSelection);
function chartSelection() {
var selection = chart.getSelection();
if (selection.length > 0) {
var row = selection[0].row;
var col = selection[0].column;
var xValue = data.getValue(row, 0);
var yValue = data.getValue(row, col);
console.log('selection: ' + xValue + ' = ' + yValue);
} else {
console.log('nothing selected');
}
}
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Hide Slice in Google Donut Chart

I am using Google Donut Chart.
In my case, sometime I will have below data
{
DATA_1: 10,
DATA_2: 15,
INVALID_DATA: 10000000 (Big Number)
}
In such case, my valid data is showing very thin or slice not visible in Charts.
Is there any option in Google Charts to hide particular Slice to make visible other slices better?
I want valid data to show percentage with INVALID_DATA, but just hiding the INVALID_DATA Slice.
there are no options on the chart itself, but hiding a slice can be done with a DataView
but cannot avoid skewing the size of the remaining slices,
relative to the hidden slice
in the following example, a column is added to calculate the % with the hidden slice
then the option pieSliceText: 'value' is used to show the true %
a DataView is used to hide the original value column, and the row with the big slice
google.charts.load('current', {
callback: function () {
var data = google.visualization.arrayToDataTable([
['Data Type', 'Value'],
['DATA_1', 10],
['DATA_2', 15],
['INVALID_DATA', 10000000]
]);
var options = {
pieHole: 0.4,
pieSliceText: 'value',
theme: 'maximized',
height: 262,
width: 262,
};
// get total -- sum
var dataGroup = google.visualization.data.group(
data,
[{column: 0, type: 'string', modifier: function () {return '';}}],
[{column: 1, type: 'number', aggregation: google.visualization.data.sum}]
);
var hideRows = [];
data.addColumn({type: 'number', label: '%'});
for (var i = 0; i < data.getNumberOfRows(); i++) {
// set % value
data.setValue(i, 2, data.getValue(i, 1) / dataGroup.getValue(0, 1));
// hide big #
if (data.getValue(i, 2) > .99) {
hideRows.push(i);
}
}
var numberFormat = new google.visualization.NumberFormat({
pattern: '#,##0.00000 %'
});
numberFormat.format(data, 2);
var dataView = new google.visualization.DataView(data);
dataView.hideColumns([1]);
dataView.hideRows(hideRows);
var pieChart = new google.visualization.PieChart(document.getElementById('pieChart_div'));
pieChart.draw(dataView, options);
var tableChart = new google.visualization.Table(document.getElementById('tableChart_div'));
tableChart.draw(data);
},
packages: ['corechart', 'table']
});
div {
padding: 2px 2px 2px 2px;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="pieChart_div"></div>
<div id="tableChart_div"></div>

How to clear chart before adding new data?

I am using the Google Visualization API. A chart is generated based on values from an ajax call function drawchart().
The user then inputs values in textboxes and this point is added on the chart also (function addUserPoint()). function addUserPoint2() is autogenerated and is also added onto the map. The result of adduserpoint and adduserpoint2 have a line between them.
My issue: If the user adds a new point again, the chart adds those values and the previously added points stay on the chart. I want to get rid of the results of adduserpoint and adduserpoint2 before adding a new point. How can I achieve this?
var chartData;
var options2;
function addUserPoint() {
if (chartData.getNumberOfColumns() === 2) {
chartData.addColumn('number', '');
}
var aa= $("#wbtotala").text();
var bb= $("#wbtotalb").text();
chartData.addRow([
parseFloat(bb),
null,
parseFloat(aa)
]);
myLineChart.draw(chartData, options2);
}
function addUserPoint2(){
if (chartData.getNumberOfColumns() === 2) {
chartData.addColumn('number', '');
}
myLineChart.draw(0,0, options2);
var aa2 = fweight;
var bb2= fcg;
chartData.addRow([
parseFloat(bb2),
null,
parseFloat(aa2)
]);
myLineChart.draw(chartData, options2);
}
function drawchart() {
document.getElementById('addPoint').addEventListener('click', addUserPoint, false);
document.getElementById('addPoint').addEventListener('click', addUserPoint2, false);
chartData = new google.visualization.DataTable();
chartData.addColumn('number', 'Sli');
chartData.addColumn('number', 'Weight');
for (var i = 0; i < chartdatax.length; i++) {
chartData.addRow([parseFloat(chartdatax[i]), parseFloat(chartdatay[i])]);
};
options2 = {
height: 500,
hAxis: {
title: 'AB',
gridlines: {
count: 20
}
},
vAxis: {
title: 'CD',
gridlines: {
count: 15
}
},
chartArea: {top:40, width: "70%", height: "75%"},
legend: { position: 'none' },
pointSize: 5
};
myLineChart = new google.visualization.LineChart(document.getElementById('myChart2'));
myLineChart.draw(chartData, options2);
}
Use the Below Command.Here data is the DataTable Variable.
var data = new google.visualization.DataTable();
Set chartData to an empty object in addUserPoint();
function addUserPoint() {
charData = {};
if (chartData.getNumberOfColumns() === 2) {
...
}
}
This makes sure that anytime you add a new Data, it clears the previous data and you have a fresh new dataset ;)

Google Chart From Json "undefined is not a function"

I am trying to work with google charts for the first time. My Json is as below
{\"cols\":[{\"id\":\"Date\",\"label\":\"Date\",\"type\":\"date\"},{\"id\":\"KeywordCount\",\"label\":\"count\",\"type\":\"number\"}],\"rows\":[{\"c\":
[{\"v\":\"new Date(2014725)\",\"f\":\"25 July 2014\"},{\"v\":\"77\",\"f\":\"77\"}]},{\"c\":
[{\"v\":\"new Date(2014724)\",\"f\":\"24 July 2014\"},{\"v\":\"101\",\"f\":\"101\"}]},{\"c\":
[{\"v\":\"new Date(2014723)\",\"f\":\"23 July 2014\"},{\"v\":\"100\",\"f\":\"100\"}]},{\"c\":
[{\"v\":\"new Date(2014722)\",\"f\":\"22 July 2014\"},
{\"v\":\"130\",\"f\":\"130\"}]}],\"p\":null}
This looks good for me, I am not able to figured it out what i am missing because i can only see an error in the chart ("undefined is not a function") . My javascript file for Google charts are
google.load('visualization', '1', { 'packages': ['corechart'] });
var postDate = $('#ReportingWall').serialize();
function drawChartAll() {
var jsonData = $.ajax({
url: '/ReportingWall/analyseStats/',
type: 'POST',
data: postDate,
dataType: 'json',
async: false,
success: function (response) {
}
}).responseText;
var data = new google.visualization.DataTable(jsonData);
console.debug(jsonData);
console.debug(data);
var chart = new google.visualization.LineChart(document.getElementById('charts_all'));
chart.draw(data, options);
var columns = [];
var series = {};
for (var i = 0; i < data.getNumberOfColumns() ; i++) {
columns.push(i);
if (i > 0) {
series[i - 1] = {};
}
}
var options = {
title: 'Keywords:',
width: 908,
legend: {
position: 'right'
},
legendFontSize: 14,
chartArea: {
left: 50,
width: '80%'
},
series: series
}
google.visualization.events.addListener(chart, 'select', function () {
var sel = chart.getSelection();
// if selection length is 0, we deselected an element
if (sel.length > 0) {
// if row is undefined, we clicked on the legend
if (sel[0].row === null) {
var col = sel[0].column;
if (columns[col] == col) {
// hide the data series
columns[col] = {
label: data.getColumnLabel(col),
type: data.getColumnType(col),
calc: function () {
return null;
}
};
// grey out the legend entry
series[col - 1].color = '#CCCCCC';
} else {
// show the data series
columns[col] = col;
series[col - 1].color = null;
}
var view = new google.visualization.DataView(data);
view.setColumns(columns);
chart.draw(view, options);
}
}
});
}
When using dates in the DataTable JSON structure, you must omit the new keyword; you are constructing a string that the Visualization API will parse into a Date object, not constructing a Date object itself.
{
"cols":[
{"id":"Date","label":"Date","type":"date"},
{"id":"KeywordCount","label":"count","type":"number"}
],
"rows":[
{"c":[{"v":"Date(2014725)","f":"25 July 2014"},{"v":77,"f":"77"}]},
{"c":[{"v":"Date(2014724)","f":"24 July 2014"},{"v":101,"f":"101"}]},
{"c":[{"v":"Date(2014723)","f":"23 July 2014"},{"v":100,"f":"100"}]},
{"c":[{"v":"Date(2014722)","f":"22 July 2014"},{"v":130,"f":"130"}]}
],
"p":null
}
If you clean it up a bit you can see in the last row you have a useless " as last char
{"cols":[
{"id":"Date","label":"Date","type":"date"},
{"id":"KeywordCount","label":"count","type":"number"}],
"rows":[
{"c":[{"v":"new Date(2014725)","f":"25 July 2014"},{"v":"77","f":"77"}]},
{"c":[{"v":"new Date(2014724)","f":"24 July 2014"},{"v":"101","f":"101"}]},
{"c":[{"v":"new Date(2014723)","f":"23 July 2014"},{"v":"100","f":"100"}]},
{"c":[{"v":"new Date(2014722)","f":"22 July 2014"},{"v":"130","f":"130"}]}],
"p":null}"
also start with a sample similar of PHP
OR this ajax
http://www.santarosa.edu/~jperetz/projects/ajax-json/

Categories

Resources