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>
Related
function drawGeoChart(scope) {
var data5 = new google.visualization.DataTable();
data5.addColumn('number', 'Latitude');
data5.addColumn('number', 'Longitude');
data5.addColumn('number', 'CountryID');
data5.addColumn('string', 'CountryName');
data5.addColumn('number', 'ColorCode');
data5.addColumn('number', 'MeetingCount');
data5.addColumn({ 'type': 'string', 'lable': 'Sentence', 'role': 'tooltip', 'p': { 'html': true } });
scope.InteractiveGraphs = vdsServices.getPreference().InteractiveGraphs;
var options = {
tooltip: { trigger: 'focus', textStyle: { fontName: attrs.tooltipfontname, fontSize: attrs.tooltipfontsize }, isHtml: true, showTitle: false },
sizeAxis: { minValue: 0, maxValue: scope.data.totalMeetings },
magnifyingGlass: { enable: true, zoomFactor: 5.0 },
legend: 'none',
enableRegionInteractivity: 'false',
keepAspectRatio: 'true',
// height: 400,
displayMode: 'markers',
width: '100%',
backgroundColor: attrs.backgroundcolor,
height: '100%',
//backgroundColor: {fill : '#F9F9F9', strokeWidth : 1},
//backgroundColor.strokeWidth
//datalessRegionColor: '#dddddd' ,
datalessRegionColor: '#ffffff',
colorAxis: { colors: colorCode, values: [1, 2, 3, 4, 5, 6] },
// isStacked: true
};
var view5 = new google.visualization.DataView(data5);
view5.hideColumns([2]);
angular.forEach(scope.data.data, function (value) {
data5.addRows([[parseInt(value.Latitude), parseInt(value.Longitude), parseInt(value.CountryId), value.CountryName, value.ColorCode, parseInt(value.MeetingCount), value.CountryName + ' | '.concat(format(value.MeetingCount)) + (value.MeetingCount > 1 ? vdsServices.getPreferLanguageProperties().MeetingsLabel : vdsServices.getPreferLanguageProperties().MeetingLabel)]]);
});
var chart = new google.visualization.GeoChart(document.getElementById('geoChartDiv'));
google.visualization.events.addListener(chart, 'ready', function () {
if(scope.InteractiveGraphs == true)
{
document.getElementById('geoChartDiv').addEventListener('mouseover',onmouseoverHandler);
google.visualization.events.addListener(chart, 'select', function() {
chartObject = chart;
var selection = chartObject.getSelection();
if (selection.length) {
graphSelectLoadMeeting(data5, selection);
$('.selectedMarketGraphList').css('display', 'block');
}
else {
// do something if the user deselects a point
// alert('deselected');
// showHideMeetingList(scope.$parent,"MeetingMarket_list","expandCollapseMarket_list",1);
// scope.$parent.$parent.getMeetingList();
// jQuery('#list').jqGrid('setGridParam', {page : 1,postData : {MeetingTypeList: '',CountryList: '',VotedList : '' }, MeetingTypeList: '',CountryList: '',VotedList : ''});
// jQuery("#list").trigger("reloadGrid");
// $("#meetingDisplayGrid").show('500');
}
});
}
});
chart.draw(view5, options);
//location.href = 'http://www.google.com?row=' + row + '&col=' + col + '&year=' + year;
}
function onmouseoverHandler() {
$("#geoChartDiv g circle").hover(function() {
$(this).css('cursor', 'pointer')
});
}
drawGeoChart(scope);
setTimeout(function() {
$('#geoChartDiv').html('');
$('#geoChartDiv').parent().width('100%');
var widthSvg = $('#geoChartLegend svg')[0].getBBox().width;
$('#geoChartLegend').width(widthSvg);
drawGeoChart(scope);
}, 500);
Here actually this code is made to get circle in google point and now I decided to make the whole region get color so for that i removed "displayMode: 'markers'," under var options and along with that I removed latitude, longitude and country id columns and rows from data5 datatable and now i am able to see the whole region get the color but once I hover over that i am unable to get the desirable output in way that is mentioned in data5.column(basically tooltip is not coming) which i used to get when display mode is in markers. Please help me how to get displayed once I hover for this region data map. I am new to javascript.
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.charts.load('current', { packages: ['corechart', 'bar'] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['DATA', 'L', 'P'],
['PCX', 18, 21],['PCG', 131, 34],['PCO', 9, 3],['PGD', 441, 269],['PAH', 1, 1],['POD', 8, 5],['PCT', 80, 180],['PDD', 1, 7],['PZZ', 3, 8],['PKK', 461, 580],['PBI', 494, 248],['PKI', 2, 5],['PKL', 5, 1] ]);
var options = {
isStacked: 'percent',
legend: { position: 'top' },
chartArea: {
left: 40,
width: '100%',
height: '75%'
},
vAxis: {
minValue: 0,
},
hAxis: {
textStyle: { fontSize: 7 }
}
};
var chart = new google.visualization.ColumnChart(document.getElementById('DataChart'));
chart.draw(data, options);
google.visualization.events.addListener(chart, 'select', selectHandler);
function selectHandler(e) {
var selection = chart.getSelection();
if (selection.length > 0) {
var mydata = data.getValue(selection[0].row,0);
alert(mydata);
//i want get key data L when klik stacked data L or P when klik stacked data P, because i want to send data
chart.setSelection([]);
}
}
}
$(window).resize(function () {
drawChart();
});
svg > g > g:last-child { pointer-events: none }
<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="DataChart" ></div>
Hello, i have a create stacked bar from google chart plugin, i want to get data when i'm click slice bar (red or blue) when i click red i get data "P" if i click blue get data "L" this demo in Js Fiddle
i'm already get data name data like PCX,PCG,PGD etc but i want get data "L" if click blue color and get data "P" when click red color. Help me thank's
to get the column label, use data table method --> getColumnLabel(colIndex)
pass the column property from the selection...
function selectHandler(e) {
var selection = chart.getSelection();
if (selection.length > 0) {
// get column label
var colLabel = data.getColumnLabel(selection[0].column);
var mydata = data.getValue(selection[0].row,0);
console.log(colLabel + ': ' + mydata);
chart.setSelection([]);
}
}
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
$(window).resize(drawChart);
drawChart();
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['DATA', 'L', 'P'],
['PCX', 18, 21],['PCG', 131, 34],['PCO', 9, 3],['PGD', 441, 269],['PAH', 1, 1],['POD', 8, 5],['PCT', 80, 180],['PDD', 1, 7],['PZZ', 3, 8],['PKK', 461, 580],['PBI', 494, 248],['PKI', 2, 5],['PKL', 5, 1] ]);
var options = {
isStacked: 'percent',
legend: { position: 'top' },
chartArea: {
left: 40,
width: '100%',
height: '75%'
},
vAxis: {
minValue: 0,
},
hAxis: {
textStyle: { fontSize: 7 }
}
};
var chart = new google.visualization.ColumnChart(document.getElementById('DataChart'));
chart.draw(data, options);
google.visualization.events.addListener(chart, 'select', selectHandler);
function selectHandler(e) {
var selection = chart.getSelection();
if (selection.length > 0) {
var colLabel = data.getColumnLabel(selection[0].column);
var mydata = data.getValue(selection[0].row,0);
console.log(colLabel + ': ' + mydata);
chart.setSelection([]);
}
}
}
<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="DataChart"></div>
In google charts document,
"If both row and column are specified, the selected element is a cell. If only row is specified, the selected element is a row. If only column is specified, the selected element is a column."
(https://developers.google.com/chart/interactive/docs/events)
In your demo, when clicking blueBar(L), selection[0].column will be 1 and the other(redBar(P)) will be 2.
Thus you can get P/L in selectHandler
var data = ['DATA', 'L', 'P']
function selectHandler(e) {
var selection = chart.getSelection();
if (selection.length > 0) {
var temp = selection[0].column
console.log(data[temp]) // temp = 1 will be 'L'; temp = 2 will be 'P'
}
}
I have an Google Annotation Chart to show relative performance of different investments. User should be able compare performance over a selected time frame, that is, the series values should be rebased / indexed to 100 at the startdate of the visible range of the chart once the timeframe is changed.
Other packages like Amcharts offer a "comparable" function, so have been looking for options like "scaleColumns" and "scaleType" in Google Docs and in other questions here, not finding any clue on how to do this.
Is there any feature I can use and might have missed, or what would be the best approach to recalculate the DataTable with index=100 upon "rangechange".
Code and screenshot is below:
google.charts.load('current', {
packages: ['corechart', 'line', 'table','annotationchart']
});
google.charts.setOnLoadCallback(drawChart);
// ---------- Chart ---------------------------- //
function drawChart() {
//data query
var query = new google.visualization.Query(
'https://docs.google.com/spreadsheets/d/1Gw67zHpKyEd1nu_V698yqYqNgE0x21_ZE_QDHJmsgtE/gviz/tq?gid=803335131&headers=1&range=A1:n451');
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var options = {
title: 'Development of the choosen Portfolio since 2008',
legend: {
textStyle : { fontSize: 8 },
maxLines : 2,
position: 'top'
},
width: '30%',
height: 700,
lineWidth: 1,
hAxis: {
format: 'M/d/yy',
title: 'Time'
},
vAxis: {
scaleType: 'log',
title: 'Return (log scale)'
},
//theme: 'maximized',
chartArea:{
left:0,
top:20,
width:'30%',
height:'85%'
},
series: {
22: {
lineWidth: 3,
color: 'red'
}
}
};
var chart = new google.visualization.AnnotationChart(document.getElementById('chart_div'))
chart.draw(data, options);
}
google.visualization.events.addListener(chart, 'rangechange', rangechange_handler);
function rangechange_handler(e) {
console.log('You changed the range to ', e['start'], ' and ', e['end']);
// How to recalculate datatable to keep index=100 for all series upon rangechange?
}
Update:
There is a way, working on it: https://groups.google.com/forum/#!searchin/google-visualization-api/compare$20zoom|sort:relevance/google-visualization-api/8HjybllsufY/z5uak6AymLcJ
After an extended period of pain got it working, hope it helps somebody: https://jsfiddle.net/AlexHorn/a9z15syr/
var viewColumns = [0];
var colors = [];
for (var i = 0; i < columnIndices.length; i++) {
viewColumns.push({
label: data.getColumnLabel(columnIndices[i]),
type: 'number',
calc: (function(x) {
// use a closure here to lock the value of i to each column
return function(dt, row) {
// return the value normalized to the first row in the view
return dt.getValue(row, columnIndices[x]) / dt.getValue(0, columnIndices[x]);
};
})(i)
});
}
I have simple column chart and I need to change color of selected (clicked) column. By default it adds white line around the column.
var options = {
title: 'Motivation and Energy Level Throughout the Day',
hAxis: {
title: 'Time of Day',
format: 'h:mm a',
viewWindow: {
min: [7, 30, 0],
max: [17, 30, 0]
}
},
vAxis: {
title: 'Rating (scale of 1-10)'
}
};
Here is simple example on jSFiddle
So if I click any column how to change its color to black?
I can't use Material Charts.
Thanks
Finally I found an answer here
Frankly I thought that there is simpler option, like setting configuration option e.g. hAxis.selected.color: '#000000'.
var chart = new google.visualization.ChartWrapper({
chartType: 'ColumnChart',
containerId: 'chart_div',
dataTable: data,
options: {
// setting the "isStacked" option to true fixes the spacing problem
isStacked: true,
height: 300,
width: 600,
series: {
1: {
// set the color to change to
color: '00A0D0',
// don't show this in the legend
visibleInLegend: false
}
}
}
});
google.visualization.events.addListener(chart, 'select', function () {
var selection = chart.getChart().getSelection();
if (selection.length > 0) {
var newSelection = [];
// if row is undefined, we selected the entire series
// otherwise, just a single element
if (typeof(selection[0].row) == 'undefined') {
newSelection.push({
column: 2
});
chart.setView({
columns: [0, {
type: 'number',
label: data.getColumnLabel(1),
calc: function () {
// this series is just a placeholder
return 0;
}
}, 1]
});
}
else {
var rows = [];
for (var i = 0; i < selection.length; i++) {
rows.push(selection[i].row);
// move the selected elements to column 2
newSelection.push({
row: selection[i].row,
column: 2
});
}
// set the view to remove the selected elements from the first series and add them to the second series
chart.setView({
columns: [0, {
type: 'number',
label: data.getColumnLabel(1),
calc: function (dt, row) {
return (rows.indexOf(row) >= 0) ? null : {v: dt.getValue(row, 1), f: dt.getFormattedValue(row, 1)};
}
}, {
type: 'number',
label: data.getColumnLabel(1),
calc: function (dt, row) {
return (rows.indexOf(row) >= 0) ? {v: dt.getValue(row, 1), f: dt.getFormattedValue(row, 1)} : null;
}
}]
});
}
// re-set the selection when the chart is done drawing
var runOnce = google.visualization.events.addListener(chart, 'ready', function () {
google.visualization.events.removeListener(runOnce);
chart.getChart().setSelection(newSelection);
});
}
else {
// if nothing is selected, clear the view to draw the base chart
chart.setView();
}
chart.draw();
});
chart.draw();
}
UPDATE:
Above solution works only if you are using a ChartWrapper.
I actually needed solution just for chart.
Finally I solved this by adding style.color to the data row. If my selected index = rowIndex then I change the color. Simple and works like a charm.
I hope it will help others.
var data = new google.visualization.DataTable();
data.addColumn({ id: 'name', type: 'string' });
data.addColumn({ id: 'm1', type: 'number' });
data.addColumn({type: 'string', role:'tooltip', 'p': {'html': true}});
data.addColumn({type: 'string', role:'style'});
$.each(scatterData.data, function (index, value) {
if (index == chartSelectedIndex) {
data.addRow([ {v:value.park}, {v:value.m1}, {v:getColumnChartHTMLTooltip(value.park,value.name,value.m1)}, 'color: #32CCFF' ]);
} else{
data.addRow([ {v:value.park}, {v:value.m1}, {v:getColumnChartHTMLTooltip(value.park,value.name,value.m1)}, null ]);
};
});
This worked for me
.my-div svg>g>g>g>g>rect {
fill: #79baeb;
}