tricky part of google charts Column with drill down functionality? - javascript

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>

Related

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/

Google chart freezes after clicking listener 2nd time

I have a problem where when I click any of the bar once it works fine, then after i close the child window and click the same bar again the chart freezes. But if at first i click a bar then click another different bar it does not freeze, until i click the same bar again
<script type="text/javascript">
google.charts.load('current', { packages: ['corechart', 'bar'] });
google.charts.setOnLoadCallback(drawBasic);
function drawBasic() {
var data = google.visualization.arrayToDataTable([
['Year', 'Remaining Items Per LOT', { role: 'style' }],
<%
Dim intValue As Integer = CInt(Rnd() * 32768)
Dim myRandom as New Random
Dim graphXSplitted As String() = graphX.Split(New String() {"|"}, StringSplitOptions.None)
Dim graphYSplitted As String() = graphY.Split(New String() {"|"}, StringSplitOptions.None)
Dim plot As String = ""
For index As Integer = 0 To graphXSplitted.Length - 2
plot += "[""" & graphXSplitted(index) & """, " & graphYSplitted(index) & ", 'stroke-color: #000000; stroke-width: 2; fill-color: #" & Hex$(myRandom.Next(1118481,8388607)) & "'],"
Next
Response.Write(plot.Remove(plot.Length - 1))
%>
]);
var options = {
title: 'Wakugai Inventory Items',
height: 300,
hAxis: {
title: 'Part Names',
direction: -1,
slantedText: true,
slantedTextAngle: 45,
textStyle: { fontSize: 12 }
},
vAxis: {
title: 'Remaining (LOT)'
},
chartArea: { left: 130, top: 10, height: '30%' }
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
google.visualization.events.addListener(chart, 'select', function () {
var category = data.getValue(chart.getSelection()[0].row, 0);
window.open("graph.aspx?x=" + category + "", "Popup", "height=400,width=1000");
});
}
</script>
the 'select' event is fired both when a bar is selected and un-selected
the first click, "selects" the bar
clicking the same bar again, "un-selects" the bar
as such, need to check the length of the selection before accessing the array contents
because chart.getSelection()[0] will be undefined when nothing is selected
google.visualization.events.addListener(chart, 'select', function () {
var selection = chart.getSelection();
if (selection.length > 0) {
var category = data.getValue(selection[0].row, 0);
window.open("graph.aspx?x=" + category + "", "Popup", "height=400,width=1000");
}
});

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 hide lines of Google line chart?

I'm using Google line chart in my project which displays different lines according to data. I want to show/hide lines when clicking their legend.
function drawSalesGraph()
{
if (sales_data_graph.length > 1)
{
graph_height = 500;
var options_graph = {
width: '1200',
height:graph_height,
colors: ['#ea6f09','#fb250d', '#0ac9c6', '#2680be', '#575bee','#6bd962','#ff0000','#000000'],
fontSize : 10,
pointSize : 10,
legend: {'position': 'right'}
};
var data = new google.visualization.arrayToDataTable(sales_data_graph);
$('#graph_sales_data').show();
}
else
{
var data = new google.visualization.DataTable();
$('#graph_sales_data').hide();
}
// Create and draw the visualization.
chart = new google.visualization.AreaChart(document.getElementById('graph_sales_data'));
chart.draw(data, options_graph);
}
I found some simple solution for this issue, so I'm sharing the code here
It's a trick using 'lineDashStyle' property of series option :)
Set the first value of lineDashStyle as 0, and second as something that greater than 0
( Google Chart Version is 45 )
... prepare the data and option for chart
// draw chart
chart.draw(data, option);
// add event handler for legend click
google.visualization.events.addListener(chart, 'click', function (e) {
var legendPrefix = 'legendentry#';
// Check if clicked legend entry
if (e.targetID.indexOf(legendPrefix) == 0) {
// index of clicked legend entry
var idx = e.targetID.substring(legendPrefix.length);
// Show line
if (option.series[idx].lineDashStyle && option.series[idx].lineDashStyle[0] == 0) {
option.series[idx].lineDashStyle = option.series[idx].originalLineDashStyle;
}
// Hide line
// ( Set the first value of lineDashStyle as 0,
// and second as something that greater than 0 )
else {
option.series[idx].originalLineDashStyle = option.series[idx].lineDashStyle;
option.series[idx].lineDashStyle = [0, 1];
}
chart.draw(data, option);
}
});
use this
vAxis: {
ridlines: {
color: 'transparent'
},
baselineColor: 'transparent'
},
Read this Answer as well or jsfiddle preview
This is how I solved my issue to hide/display line when clicked on its respective legend title.
/*****drawChart is used to Draw Graph.******/
function drawChart() {
if (sales_data_graph.length > 1)
{
$('#graph_sales_data').show();
var data = new google.visualization.arrayToDataTable(sales_data_graph);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ChartWrapper({
chartType: 'LineChart',
containerId: 'graph_sales_data',
dataTable: data,
colors: ['#ea6f09', '#fb250d', '#0ac9c6', '#2680be', '#575bee', '#6bd962', '#ff0000', '#000000'],
options: {
width: 1200,
height: 500,
fontSize: 10,
pointSize: 10
}
});
// create columns array
var columns = [0];
/* the series map is an array of data series
* "column" is the index of the data column to use for the series
* "roleColumns" is an array of column indices corresponding to columns with roles that are associated with this data series
* "display" is a boolean, set to true to make the series visible on the initial draw
*/
var seriesMap = [{
column: 1,
roleColumns: [1],
display: true
}, {
column: 2,
roleColumns: [2],
display: true
}, {
column: 3,
roleColumns: [3],
display: true
}, {
column: 4,
roleColumns: [4],
display: true
}, {
column: 5,
roleColumns: [5],
display: true
}, {
column: 6,
roleColumns: [6],
display: true
}, {
column: 7,
roleColumns: [7],
display: true
}, {
column: 8,
roleColumns: [8],
display: true
}];
var columnsMap = {};
var series = [];
for (var i = 0; i < seriesMap.length; i++) {
var col = seriesMap[i].column;
columnsMap[col] = i;
// set the default series option
series[i] = {};
if (seriesMap[i].display) {
// if the column is the domain column or in the default list, display the series
columns.push(col);
}
else {
// otherwise, hide it
columns.push({
label: data.getColumnLabel(col),
type: data.getColumnType(col),
sourceColumn: col,
calc: function() {
return null;
}
});
// backup the default color (if set)
if (typeof(series[i].color) !== 'undefined') {
series[i].backupColor = series[i].color;
}
series[i].color = '#CCCCCC';
}
for (var j = 0; j < seriesMap[i].roleColumns.length; j++) {
//columns.push(seriesMap[i].roleColumns[j]);
}
}
chart.setOption('series', series);
function showHideSeries() {
var sel = chart.getChart().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 (typeof(columns[col]) == 'number') {
var src = columns[col];
// hide the data series
columns[col] = {
label: data.getColumnLabel(src),
type: data.getColumnType(src),
sourceColumn: src,
calc: function() {
return null;
}
};
// grey out the legend entry
series[columnsMap[src]].color = '#CCCCCC';
}
else {
var src = columns[col].sourceColumn;
// show the data series
columns[col] = src;
series[columnsMap[src]].color = null;
}
var view = chart.getView() || {};
view.columns = columns;
chart.setView(view);
chart.draw();
}
}
}
google.visualization.events.addListener(chart, 'select', showHideSeries);
// create a view with the default columns
var view = {
columns: columns
};
chart.draw();
}
else
{
$('#graph_sales_data').hide();
}
}

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