Google chart javascript - javascript

I'm using Google Charts for a small projects for myself, and I'm not very good with javascript so I thought I'd ask for some help.
Basically I want to change the current values of the chart by pressing a button.
This is the script:
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['', 'YES', 'NO'],
['', 5, 2],
]);
var options = {
title: 'Win / Loss ratio',
vAxis: {title: 'Chart', titleTextStyle: {color: 'red'}}
};
var chart = new google.visualization.BarChart(document.getElementById('chart'));
chart.draw(data, options);
}
The values 5 and 2 should be changed when clicking button_1 or button_2
All help is appreciated.

You can do something like this:
function drawChart() {
var data = google.visualization.arrayToDataTable([
['', 'YES', 'NO'],
['', 5, 2],
]);
var options = {
title: 'Win / Loss ratio',
vAxis: {title: 'Chart', titleTextStyle: {color: 'red'}}
};
var chart = new google.visualization.BarChart(document.getElementById('chart'));
chart.draw(data, options);
function incrementYes () {
data.setValue(0, 1, data.getValue(0, 1) + 1);
chart.draw(data, options);
}
function incrementNo () {
data.setValue(0, 2, data.getValue(0, 2) + 1);
chart.draw(data, options);
}
// assumes button_1 and button_2 have id's "button_1" and "button_2"
var btn1 = document.querySelector('#button_1');
var btn2 = document.querySelector('#button_2');
if (document.addEventListener) {
// add event listener in most browsers
btn1.addEventListener('click', incrementYes);
btn2.addEventListener('click', incrementNo);
}
else if (document.attachEvent) {
// add event listener in IE
btn1.attachEvent('onclick', incrementYes);
btn2.attachEvent('onclick', incrementNo);
}
else {
// add event listener in legacy browsers
btn1.onclick = incrementYes;
btn2.onclick = incrementNo;
}
}

Related

How to place an icon inside Google ColumnChart

I have columnchart bar which has one column and I wanna place an icon top of the bar.This bar is dynamically changing as randomly.I checked some sources on the internet and Google Chart API but couldn't find a solution.Is there any way to do that?Below you can see the code belongs to my chart
Here it's demo to give you idea about my Grid and Chart also
https://stackblitz.com/edit/angular-pt2kha?file=app/grid-list-overview-example.html
Here what I expect to see
What I tried below to generate this Column Chart below
TS File
title= 'Temperature';
type = 'ColumnChart';
data= [['',25]];
columnNames= ['Element', 'Temperature'];
options= {
backgroundColor: '#fafafa',
legend: {position: 'none'},
animation: {
duration: 250,
easing: 'ease-in-out',
startup: true,
},
bar: {
groupWidth: 50
},
hAxis: {
baselineColor: 'none',
ticks: []
},
vAxis: {
baselineColor: 'none',
ticks: [],
viewWindow: {
max:40,
min:0
}
}
}
width=100;
height=300;
ngOnInit()
{
interval(2000).subscribe(()=>{
this.data = [
['', (Math.random() * 41)],
];
});
}
HTML File
<div style="border-style:solid;border-width:1px;">
<google-chart #chart
[title]="title"
[type]="type"
[data]="data"
[columnNames]="columnNames"
[options]="options"
[width]="width"
[height]="height"
>
</google-chart>
</div>
you can add icons using chart methods getChartLayoutInterface() & getBoundingBox()
on the chart's 'ready' event, find the position of the bar,
then place the image.
although not angular, it will work the same,
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = new google.visualization.DataTable();
data.addColumn('string', 'X');
data.addColumn('number', 'Y');
data.addRows([
[{v: 'a', p: {thumb: 'clone_old.png'}}, 20],
[{v: 'b', p: {thumb: 'boba_fett.png'}}, 15],
[{v: 'c', p: {thumb: 'jango_fett.png'}}, 30],
[{v: 'd', p: {thumb: 'clone_3.png'}}, 5],
[{v: 'e', p: {thumb: 'clone_2.png'}}, 25]
]);
var options = {
legend: 'none'
};
var container = document.getElementById('chart_div');
var containerBounds = container.getBoundingClientRect();
var chart = new google.visualization.ColumnChart(container);
google.visualization.events.addListener(chart, 'ready', function () {
var chartLayout = chart.getChartLayoutInterface();
for (var i = 0; i < data.getNumberOfRows(); i++) {
var barBounds = chartLayout.getBoundingBox('bar#0#' + i);
var path = 'http://findicons.com/files/icons/512/star_wars/32/';
var thumb = container.appendChild(document.createElement('img'));
thumb.src = path + data.getProperty(i, 0, 'thumb');
thumb.style.position = 'absolute';
thumb.style.top = (barBounds.top + containerBounds.top - 40) + 'px';
thumb.style.left = (barBounds.left + containerBounds.left + (barBounds.width / 2) - 16) + 'px';
}
});
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
`

Google Charts: Problem handling a 'click' event

I have a Google Chart, a bar chart, that I recently extended so that selecting one of the bars will open a new page, showing the data corresponding to that bar. I used the guidelines for basic interactivity, using a selectHandler to process the event.
I then decided to do the same thing when clicking on one of the labels, but I have not been able to get this to work. I looked pretty carefully at the docs, and at this older question (which is, in fact, my actual question: how do I make a hyperlink out of the chart's labels?) for guidance. I added a Listener for click events, and a handler for this, but my chart is not responding to them.
My basic setup is:
google.charts.load('current', {
callback: drawChart,
packages: ['bar']
});
var books = [
['2018-07', 5, 98.0],
['2018-08', 5, 100.0], // etc.
];
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Date');
data.addColumn('number', 'Number Purchased');
data.addColumn('number', 'Price Paid');
data.addRows(books);
var options = {
chart: {
title: 'Book Purchases',
},
width: 800,
height: 800,
bars: 'horizontal',
series: {
0: {
axis: 'purchased'
},
1: {
axis: 'price_paid'
}
},
axes: {
x: {
purchased: {
side: 'top',
label: 'Number Purchased'
},
price_paid: {
label: 'Price Paid'
}
}
}
};
function selectHandler() {
var selectedItem = chart.getSelection()[0];
if (selectedItem) {
var date = data.getValue(selectedItem.row, 0);
var query_string = '?date=' + date;
var path = window.location.pathname;
path = path.replace("bookgraph", "");
path = path + "search" + query_string;
var newURL = window.location.protocol + "//" + window.location.host + path;
window.open(newURL, '_blank');
}
}
function clickHandler(e) {
alert('The user has clicked on ' + e.targetID);
}
var chart = new google.charts.Bar(document.getElementById('bookgraph_material'));
google.visualization.events.addListener(chart, 'click', clickHandler);
google.visualization.events.addListener(chart, 'select', selectHandler);
chart.draw(data, options);
The selectHandler works fine. But I can't even get the clickHandler to show the alert (after this works, I'll actually code the rest of it); it's apparently never fired, regardless of where I click. What am I doing wrong?
I set up a JS Fiddle page for this, to experiment with, with an HTML frame so it'll actually work; this shows the working select (albeit to a 404, of course) and the nonworking click.
Thanks.
the 'click' event is not supported by Material charts,
see issue #: 2257...
and there are several configuration options that are not supported as well,
see issue #: 2143...
Material = google.charts.Bar -- packages: ['bar']
Classic = google.visualization.BarChart -- packages: ['corechart']
one work around would be to use a Classic chart with option --> theme: 'material'
or register your own click event,
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['bar']
});
var books = [
['2016-01', 3, 45.0],
['2016-02', 3, 56.0],
['2016-03', 1, 23.0],
['2016-04', 4, 60.0],
['2016-05', 1, 0],
['2016-06', 3, 14.0],
['2016-07', 4, 65.0],
['2016-08', 1, 15.0],
['2016-09', 13, 234.0],
['2016-10', 20, 834.0],
['2016-11', 5, 115.0],
['2016-12', 5, 58.0],
['2017-01', 6, 122.0],
['2017-02', 4, 84.0],
['2017-03', 1, 0],
['2017-04', 1, 30.0],
['2017-05', 2, 38.0],
['2017-06', 1, 11.0],
['2017-07', 0, 0],
['2017-08', 4, 88.0],
['2017-09', 5, 89.0],
['2017-10', 4, 73.0],
['2017-11', 5, 79.0],
['2017-12', 2, 37.0],
['2018-01', 1, 22.0],
['2018-02', 5, 98.0],
['2018-03', 5, 132.0],
['2018-04', 3, 56.0],
['2018-05', 14, 272.0],
['2018-06', 4, 88.0],
['2018-07', 5, 98.0],
['2018-08', 5, 100.0],
];
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Date');
data.addColumn('number', 'Number Purchased');
data.addColumn('number', 'Price Paid');
data.addRows(books);
var options = {
chart: {
title: 'Book Purchases',
},
width: 800,
height: 800,
bars: 'horizontal',
series: {
0: {
axis: 'purchased'
},
1: {
axis: 'price_paid'
}
},
axes: {
x: {
purchased: {
side: 'top',
label: 'Number Purchased'
},
price_paid: {
label: 'Price Paid'
}
}
}
};
function selectHandler() {
var selectedItem = chart.getSelection()[0];
if (selectedItem) {
var date = data.getValue(selectedItem.row, 0);
var query_string = '?date=' + date;
var path = window.location.pathname;
path = path.replace("bookgraph", "");
path = path + "search" + query_string;
var newURL = window.location.protocol + "//" + window.location.host + path;
window.open(newURL, '_blank');
}
}
function clickHandler(e) {
if (e.target.tagName === 'text') {
console.log(e.target.textContent);
}
}
var container = document.getElementById('bookgraph_material');
var chart = new google.charts.Bar(container);
google.visualization.events.addListener(chart, 'select', selectHandler);
container.addEventListener('click', clickHandler);
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="bookgraph_material"></div>

Google GeoCharts Colors Not Working

I have tried multiple things to apply but none of them seem to work to change my charts. I am uploading the array through a file and everything seems to work, even changing the defaultColor, but colorAxis does not seem to work. Could you guys(and girls) help me I would be grateful. Thanks
/* CSV handling - START */
var processedData = [];
var continent = $('select[name="continents"] option:selected').val();
$.get('example.csv', function(data) {
processedData = $.csv.toArrays(data);
}, 'text');
/* CSV handling - END */
/* Google Charts */
google.charts.load('current', {
'packages':['geochart'],
// Note: you will need to get a mapsApiKey for your project.
// See: https://developers.google.com/chart/interactive/docs/basic_load_libs#load-settings
'mapsApiKey': //doesn't matter
});
google.charts.setOnLoadCallback(drawRegionsMap);
function drawRegionsMap() {
var data = google.visualization.arrayToDataTable(processedData, false);
var options = {
sizeAxis: { minValue: 0, maxValue: 100 },
colorAxis: {colors: ['#e7711c', '#4374e0']},
region: continent,
width: '100%',
height: '100%',
backgroundColor: 'none'
};
var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
/* Google Charts - End */
Please Refer To Google Developer reference
https://developers.google.com/chart/interactive/docs/gallery/geochart#important
var options = {
region: '002', // Africa
colorAxis: {colors: ['#00853f', 'black', '#e31b23']},
backgroundColor: '#81d4fa',
datalessRegionColor: '#f8bbd0',
defaultColor: '#f5f5f5',
};
https://developers.google.com/chart/interactive/docs/gallery/geochart#coloring-your-chart
var options = {
region: 'IT',
displayMode: 'markers',
colorAxis: {colors: ['green', 'blue']}
};
var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
chart.draw(data, options);
using the data from the comment, the chart colors seem to work
recommend removing the options for sizeAxis
the values in the data table range from 100 to 2313 (not 0 to 100),
the chart will handle by default
see following working snippet...
google.charts.load('current', {
callback: function () {
var processedData = [
['Country','Popularity'],
['HR',300.00],
['RU',100.00],
['FR',200.00],
['BR',2000.00],
['DZ',222.00],
['US',333.00],
['DE',555.00],
['DD',999.00],
['SZ',2313.00],
['AU',2222.00],
['BM',400.00],
['CA',322.00]
];
var data = google.visualization.arrayToDataTable(processedData);
var sizeRange = data.getColumnRange(1);
var options = {
colorAxis: {colors: ['#e7711c', '#4374e0']},
//region: continent,
width: '100%',
height: '100%',
backgroundColor: 'none'
};
var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
chart.draw(data, options);
},
packages: ['geochart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Hierarchies graphs in google charts

How can I build something like this (with subcategories on the one of the axis)
although the requested layout is not available via standard configuration options,
it is possible to achieve, if you're ok with modifying the svg manually
when the chart's 'ready' event fires, add the category labels and group lines
see following working snippet, which is just an example to show the possibility
several assumptions are made based on the size and placement of the chart...
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['State', 'Store', 'Sales'],
['California', 'Donald\'s Market', 1560],
['California', 'Alexei\'s Specialties', 1090],
['California', '24-Seven', 345],
['Texas', 'Albert Market', 245],
['Texas', 'Jim\'s Market', 245],
['Texas', 'International Food Store', 82]
]);
var options = {
bars: 'horizontal',
chartArea: {
left: 204
},
height: 400,
vAxis: {
textStyle: {
fontSize: 10
}
}
};
var chartDiv = document.getElementById('chart_div');
var chart = new google.visualization.BarChart(chartDiv);
var view = new google.visualization.DataView(data);
view.setColumns([1, 2, {
calc: 'stringify',
sourceColumn: 2,
type: 'string',
role: 'annotation'
}]);
google.visualization.events.addListener(chart, 'ready', function () {
var rowIndex = -1;
var stateValue = '';
var svgParent = chartDiv.getElementsByTagName('svg')[0];
Array.prototype.forEach.call(chartDiv.getElementsByTagName('text'), function(text) {
var groupLabel;
if ((text.getAttribute('text-anchor') === 'end') &&
(parseFloat(text.getAttribute('x')) < 200)) {
rowIndex++;
if (stateValue !== data.getValue(rowIndex, 0)) {
stateValue = data.getValue(rowIndex, 0);
groupLabel = text.cloneNode(true);
groupLabel.setAttribute('x', '60');
groupLabel.innerHTML = stateValue;
svgParent.appendChild(groupLabel);
addGroupLine(groupLabel, -24);
}
if (rowIndex === (data.getNumberOfRows() - 1)) {
addGroupLine(text, 16);
}
}
});
function addGroupLine(text, yOffset) {
var groupLine = chartDiv.getElementsByTagName('rect')[0].cloneNode(true);
groupLine.setAttribute('y', parseFloat(text.getAttribute('y')) + yOffset);
groupLine.setAttribute('x', '16');
groupLine.setAttribute('height', '0.8');
groupLine.setAttribute('width', '188');
groupLine.setAttribute('stroke', 'none');
groupLine.setAttribute('stroke-width', '0');
groupLine.setAttribute('fill', '#000000');
svgParent.appendChild(groupLine);
}
});
chart.draw(view, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Not able to click on label in google chart api

I am new to javascript and i am using google chart api for creating charts. i wanted to click on left side label that shows in below image. so, my question is that can we click on left side label?
give me some idea for this. if it is possible then help me.
function drawStackedChart(reqCategoryId,fcategoryName)
{
$.ajax({
url: "http://localhost:8080/TheSanshaWorld/sfcms/fetch-complaint-result-for-other-category?categoryId="+reqCategoryId,
datatype: "json",
success : function(jsonData)
{
var data = new google.visualization.DataTable();
// Add columns
data.addColumn('string','categoryName');
data.addColumn({type: 'number',role: 'interval'});
var complaintStatus = jsonData[0].complaintStatus;
for(var i=0;i<complaintStatus.length;i++)
{
data.addColumn('number',complaintStatus[i].statusName);
data.addColumn({type: 'number',role: 'scope'});
}
data.addRows(jsonData.length);
var maxVal=jsonData[0].totalCountComplaint;
for(i=0;i<jsonData.length;i++)
{
// trying to create hyperlink
data.setCell(i,0,'+jsonData[i].categoryName+');
data.setCell(i,1,jsonData[i].categoryId);
for(j=0; j< jsonData[i].complaintStatus.length; j++)
{
data.setCell(i,parseInt(jsonData[i].complaintStatus[j].statusId)*2, jsonData[i].complaintStatus[j].countComplaint);
data.setCell(i,parseInt(jsonData[i].complaintStatus[j].statusId)*2+1, jsonData[i].complaintStatus[j].statusId);
}
if(jsonData[i].totalCountComplaint>maxVal)
maxVal=jsonData[i].totalCountComplaint;
}
var options = {
title : fcategoryName+' Complaints Dashboard',
titleTextStyle : {
fontName : 'Arial',
fontSize : 18,
bold : true,
},
isStacked:true,
chartArea: {width:'50%',height:'75%'},
bar: {groupWidth: '50%'},
tooltip : {
isHtml : true,
textStyle : {
fontName : 'sans-serif',
fontSize : 14,
bold : false
}
},
hAxis:{
title:'status values',
gridlines : {
count : maxVal+1
},
baseline:maxVal,//static
},
vAxis:{
title:'Complaint\'s categories',
textStyle : {
fontName : 'sans-serif',
fontSize : 18,
bold : false,
},
},
};
var chart = new google.visualization.BarChart(document.getElementById('donutchart'));
chart.draw(data, options);
new google.visualization.events.addListener(chart, 'select', selectionHandler);
function selectionHandler() {
// code for selection handler
}
you can use the targetID of the 'click' event to find the label that was clicked
when a y-axis label is clicked, the targetID will hold a value similar to the following...
vAxis#0#label#0
you can use the string method split, to find the label value in the data
selection = e.targetID.split('#');
when the first value = vAxis, this means a y-axis label was clicked
if (selection[0].indexOf('vAxis') > -1) {
the first integer refers to the y-axis, in this example, there is only one
the second integer refers to the row in the data
to get the value clicked...
data.getValue(rowIndex, colIndex);
e.g.
data.getValue(parseInt(selection[selection.length - 1]), parseInt(selection[1])));
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages:['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Element', 'Density', { role: 'style' } ],
['Copper', 8.94, '#b87333'],
['Silver', 10.49, 'silver'],
['Gold', 19.30, 'gold'],
['Platinum', 21.45, 'color: #e5e4e2']
]);
var options = {
title: 'Density of Precious Metals, in g/cm^3',
width: 600,
height: 400,
bar: {groupWidth: '95%'},
legend: { position: 'none' },
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
google.visualization.events.addListener(chart, 'click', function(e) {
var selection;
if (e.targetID) {
selection = e.targetID.split('#');
if (selection[0].indexOf('vAxis') > -1) {
console.log('label clicked = ' + data.getValue(parseInt(selection[selection.length - 1]), parseInt(selection[1])));
}
}
});
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Categories

Resources