Show/hide lines/data in Google Chart - javascript

I'm trying to make a google line chart with 2 lines in it.
You should be able to turn them on and off(show/hide) by two checkboxes..
Anyone got any idea show to make this, og just give some pointers?
My guess would be some onClick jQuery stuff?
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
]);
var options = {
title: 'Company Performance'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>

try this
Mark up:
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
<button type="button" id="hideSales" >Hide Sales</button>
<button type="button" id="hideExpenses" >Hide Expence</button>
</body>
Script:
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
]);
var options = {
title: 'Company Performance'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
var hideSal = document.getElementById("hideSales");
hideSal.onclick = function()
{
view = new google.visualization.DataView(data);
view.hideColumns([1]);
chart.draw(view, options);
}
var hideExp = document.getElementById("hideExpenses");
hideExp.onclick = function()
{
view = new google.visualization.DataView(data);
view.hideColumns([2]);
chart.draw(view, options);
}
}
</script>

To get your required output check this code.
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 null, 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);
}
}
});
Instead of having a checkbox, use the legend to hide/show the lines.

Recently the behavior of the select event changed so Abinaya Selvaraju's answer needs a slight fix
if (typeof sel[0].row === 'undefined') {
...
}
becomes
if (sel[0].row == null) {
...
}

I updated the solution provided by Shinov T to allow real toggling (show/hide) of columns. You can see the result in this fiddle.
I added this code to save the current state of each column to allow toggleing:
var toggleSales = document.getElementById("toggleSales");
var salesHidden = false;
toggleSales.onclick = function() {
salesHidden = !salesHidden;
view = new google.visualization.DataView(data);
if (salesHidden) {
view.hideColumns([1]);
}
chart.draw(view, options);
}
var toggleExp = document.getElementById("toggleExpenses");
var expHidden = false;
toggleExp.onclick = function() {
expHidden = !expHidden;
view = new google.visualization.DataView(data);
if (expHidden) {
view.hideColumns([2]);
}
chart.draw(view, options);
}

Related

Google Chart Background

I have this 2 googlecharts in my program:
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
var matrix = [];
for(var i=0; i<50; i++) {
matrix[i] = new Array(2);
}
var j=0;
$.getJSON("x.json",function(data){
$.each(data, function(key, val){
matrix[j][0]=(val.y);
matrix[j][1]=(val.z);
j++;
});
});
// Draw the chart and set the chart values
function drawChart() {
var data = google.visualization.arrayToDataTable([
['a', 'b'],
[matrix[0][0], matrix[0][1]],
[matrix[1][0], matrix[1][1]],
[matrix[2][0], matrix[2][1]],
[matrix[3][0], matrix[3][1]],
[matrix[4][0], matrix[4][1]]
]);
// Set chart options
var options = {'title':'h',
'width':900,
'height':400,
is3D: true,
};
// Display the chart inside the <div> element with id="piechart"
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load("current", {packages:['corechart']});
google.charts.setOnLoadCallback(drawChart);
var matrix = [];
for(var i=0; i<50; i++) {
matrix[i] = new Array(2);
}
var j=0;
$.getJSON("x.json",function(data){
$.each(data, function(key, val){
matrix[j][0]=(val.y);
matrix[j][1]=(val.z);
j++;
});
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
["Element", "Density", { role: "style" } ],
[matrix[0][0], matrix[0][1], "red"],
[matrix[1][0], matrix[1][1], "yellow"],
[matrix[2][0], matrix[2][1], "green"],
[matrix[3][0], matrix[3][1], "grey"]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{ calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation" },
2]);
var options = {
title: "k",
width: 800,
height: 300,
bar: {groupWidth: "95%"},
legend: { position: "none" }
};
var chart = new google.visualization.ColumnChart(document.getElementById("columnchart_values"));
chart.draw(view, options);
<!--options-->
}
</script>
<div id="columnchart_values" style="width: 900px; height: 800px; display: inline-block;"></div>
</div>
I want to change the background color of both.
I've tryed some of the solutions for background color change, like adding the background color to the options, adding a chart area and using the chart.draw(data, google.charts.Bar.convertOptions(options)) method.
But the chart simple disapears.
Any solution for this?
You can change Google Chart Color By write in backgroundColor in your option, for example -by using your code-:
var options = {
'backgroundColor': 'blue',
};
var chart = new
google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
for your first snippet code, you can check this work color in fiddle

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>

Google Chart : Unable to get property 'arrayToDataTable'

I want to show google chart using data that i acquired from SQL server using javascript. But i got IE error "Unable to get property arrayToDataTable" even i already add google chart JS. I already check the data by alert it, and the data is ok. How to fix this?
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
var array = loadData();
google.load("visualization", "1.1", {packages:["bar"]});
google.setOnLoadCallback(drawChart(array));
function loadData(){
var array = [
['Year', 'Sales', 'Expenses', 'Profit']
];
//Connection
var connection = new ActiveXObject("ADODB.Connection") ;
var connectionstring="Provider=SQLOLEDB.1;Password=Password1234;Persist Security Info=True;User ID=sa;Initial Catalog=all_data;Data Source=172.16.11.90";
connection.Open(connectionstring);
var rs = new ActiveXObject("ADODB.Recordset");
rs.Open("SELECT * FROM bar_chart", connection);
rs.MoveFirst;
while(!rs.eof)
{
array.push([rs.fields(0), parseInt(rs.fields(1)), parseInt(rs.fields(2)), parseInt(rs.fields(3))]);
rs.movenext;
}
rs.close;
connection.close;
return array;
}
function drawChart(x) {
alert(x[4][3]);
var data = google.visualization.arrayToDataTable(x);
var options = {
chart: {
title: 'Company Performance',
subtitle: 'Sales, Expenses, and Profit: 2014-2017'
},
bars: 'horizontal' // Required for Material Bar Charts.
};
var chart = new google.charts.Bar(document.getElementById('barchart_material'));
chart.draw(data, options);
}
</script>
And here is my html:
<body>
<div id="barchart_material" style="width: 900px; height: 500px;"></div>
</body>
This error occurs since google.setOnLoadCallback function expects a callback as an argument.
Replace:
var array = loadData();
google.setOnLoadCallback(drawChart(array));
In this case drawChart function is invoked immediately without
waiting google visualization API to load
with:
google.setOnLoadCallback(function () {
var array = loadData();
drawChart(array);
});
Example
google.load("visualization", "1.1", { packages: ["bar"] });
google.setOnLoadCallback(function () {
var data = generateData();
drawChart(data);
});
function generateData() {
var data = [
['Year', 'Sales', 'Expenses', 'Profit']
];
for (var year = 2000; year < 2010; year++) {
data.push([year.toString(), getRandomArbitrary(100, 200), getRandomArbitrary(100, 400), getRandomArbitrary(100, 500)]);
}
return data;
}
function drawChart(data) {
var dataTable = google.visualization.arrayToDataTable(data);
var options = {
chart: {
title: 'Company Performance',
subtitle: 'Sales, Expenses, and Profit: 2014-2017'
},
bars: 'horizontal' // Required for Material Bar Charts.
};
var chart = new google.charts.Bar(document.getElementById('barchart_material'));
chart.draw(dataTable, options);
}
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="barchart_material" style="width: 900px; height: 500px;"></div>

How to get HtmlUnit to update page after javascript has finished

I am trying to load the contents of a div which changes when a listener is triggered.
The java code I currently have is:
public static void main(String arg[]) throws IOException{
String url = "http://localhost/chartsTest/test.html";
WebClient wc = new WebClient();
HtmlPage p = null;
try {
System.out.println("Attempting to load page: " + url);
p = wc.getPage(url);
System.out.println("Sucsess!");
} catch (Exception e) {
System.err.println("Failed to get page");
}
JavaScriptJobManager m = p.getEnclosingWindow().getJobManager();
int c;
while ((c = m.getJobCount()) > 0){
System.out.println("Jobs: " + c);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
}
div = p.getHtmlElementById("test");
content = div.asText();
System.out.println(content);
wc.close();
}
and my test.html page (which loads a google chart) is:
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", '1', {packages:['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
// var query = new google.visualization.Query('simpleexample?tq=select name,population');
// query.send(handleSimpleDsResponse);
handleSimpleDsResponse(true);
function handleSimpleDsResponse(response) {
// var data = response.getDataTable();
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses'],
['2013', 1000, 400],
['2014', 1170, 460],
['2015', 660, 1120],
['2016', 1030, 540]
]);
var chart_div = document.getElementById('chart_div');
var chart_data = document.getElementById('chart_data');
var test = document.getElementById('test');
var chart = new google.visualization.AreaChart(chart_div);
// Wait for the chart to finish drawing before calling the getImageURI() method.
google.visualization.events.addListener(chart, 'ready', function () {
chart_div.innerHTML = '<img src="' + chart.getImageURI() + '">';
chart_data.innerHTML = chart.getImageURI();
test.innerHTML = "after";
});
chart.draw(data);
}
}
</script>
</head>
<body>
<div id="test">before</div>
<div id='chart_div'></div>
<div id="chart_data"></div>
</body>
</html>
but when I print the div it always equals before and not after. How can I get the value for after the chart has finished loading?
This is a bug of handling Promise.resolve(), and it has been fixed in SVN.
Please use new WebClient(BrowserVersion.CHROME), with the latest build or snapshot.
There is no need to wait(), as it is not AJAX-based.

Multiple Instances of Google Visualizations Chart Inside Separate Divs [Followup]

This is a followup to a question I've already asked on StackOverflow. So please make sure you read that one to get the whole picture:
Multiple Instances of Google Visualizations Chart Inside Separate Divs
So in an attempt to make this whole thing dynamic, I wrote the following code:
var containers = document.getElementsByClassName('gaugeWrapper');
console.log(containers);
google.load('visualization', '1', { packages: ['gauge'] });
for(var i = 0; i < containers.length; i++) {
var id = containers[i].getAttribute('id');
var name = containers[i].getAttribute('data-name');
var value = containers[i].getAttribute('data-value');
google.setOnLoadCallback(function () { drawChart(id, name, value) });
}
function drawChart(id, name, value) {
console.log(id);
console.log(name);
console.log(value);
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
[name, value]
]);
var options = {
width: 400, height: 120,
redFrom: 90, redTo: 100,
yellowFrom: 75, yellowTo: 90,
minorTicks: 5
};
var chart = new google.visualization.Gauge(document.getElementById(id));
chart.draw(data, options);
}
This does not work. The problem is that the console outputs the data of the last div only. Which means that the function is being called 5 (containers.length) times with the same set of parameters.
UPDATE:
As per Ateszki's answer, here's my updated code:
google.load('visualization', '1', { packages: ['gauge'] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var containers = document.getElementsByClassName('gaugeWrapper');
for (var i = 0; i < containers.length; i++) {
var id = containers[i].getAttribute('id');
var name = containers[i].getAttribute('data-name');
var value = containers[i].getAttribute('data-value');
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
[name, value]
]);
var options = {
width: 400, height: 120,
redFrom: 90, redTo: 100,
yellowFrom: 75, yellowTo: 90,
minorTicks: 5
};
var cont = document.getElementById(id);
console.log(cont);
var chart = new google.visualization.Gauge(cont);
chart.draw(data, options);
}
}
Unfortunately, I still couldn't get it to work, yet. Now nothing renders on the screen, although my console.log's seem to output the right things...
Any explanations/suggestions?
The function that you are binding onload is overwriting the previous one.
Maybe you can store the values in another object and load them all at once in one function.
Ok the following has solved the problem:
google.load('visualization', '1', { packages: ['gauge'] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var containers = $('.gaugeWrapper');
containers.each(function (index, elem) {
var id = $(elem).attr('id');
var name = $(elem).data('name');
var value = $(elem).data('value');
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
[name, value]
]);
var options = {
width: 400, height: 120,
redFrom: 90, redTo: 100,
yellowFrom: 75, yellowTo: 90,
minorTicks: 5
};
var cont = document.getElementById(id);
var chart = new google.visualization.Gauge(cont);
chart.draw(data, options);
});
I do not know how it differs from the code in the updated section of the question except for the fact that I am now using jQuery to grab the values I'm looking for...

Categories

Resources