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'
}
}
Related
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>
`
I am trying to use Material Bar Chart, because i want to change K format for thousands at the Vaxis data. I want to show as 1000 not like 1k. When I use the following code for the chart, it seems okey, but i cannot customize Vaxis;
<script>
Array.prototype.insert = function ( index, item ) {
this.splice( index, 0, item );
};
function all(arr2,test){
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
if(arrGrp[0].length == 2)
{
arr2.push([' ', null]);
}
var data = google.visualization.arrayToDataTable(arr2);
console.log("ARR: " + arr2);
var options = {
title: 'Min: ' + min +' Max: ' + max ,
bars:'vertical',
bar: {groupWidth: "25%"},
height: 400,
vAxis: {
format: 'decimal',
minValue: min,
maxValue: max,
viewWindowMode : 'explicit',
viewWindow: {
max:max,
min:min
},}};
var chart = new google.charts.Bar(document.getElementById('chart_div'));
chart.draw(data, options);
}
}
var arrGrp=[];
</script>
And I populate my data as follows;
#{
var grpHeader2 = Model.GroupBy(r => new { r.GradeId, r.Grade }).ToList();
<script>
var arr = [];
var rowIndex=0;
arr.insert(rowIndex,'Date');
rowIndex++;
#foreach (var grpHeaderItem in grpHeader2)
{
<text>
arr.insert(rowIndex,'#(Html.Raw(grpHeaderItem.Key.Grade))');
rowIndex++;
</text>
}
arrGrp.push(arr);
max='#(Model.Max(r=>r.MaxScore).HasValue ? Model.Max(r => r.MaxScore) : -1 )';
min='#(Model.Min(r=>r.MinScore).HasValue ? Model.Min(r => r.MinScore) : -1 )';
</script>
}
#foreach (var item in Model.GroupBy(r => new { r.PlannedDate }))
{
<script>
var arr = [];
var rowIndex=0;
#*arr.insert(rowIndex,new Date(#item.Key.PlannedDate.Year,#item.Key.PlannedDate.Month,#item.Key.PlannedDate.Day));*#
arr.insert(rowIndex,'#item.Key.PlannedDate.ToString("dd.MM.yyyy")');
rowIndex++;
#foreach (var grpHeaderItem in grpHeader2)
{
<text>
arr.insert(rowIndex,#(Model.Where(r=>r.PlannedDate == item.Key.PlannedDate && grpHeaderItem.Key.GradeId == r.GradeId).Select(r=>r.GradeMin).FirstOrDefault()));
rowIndex++;
</text>
}
arrGrp.push(arr);
</script>
}
#{
<script>
all(arrGrp,'#(Html.Raw(ViewBag.Exam))');
</script>
Screen shot is [1]: https://imgyukle.com/i/1.xElyj "before - working but no customization"
But when change code
chart.draw(data, options);
to
chart.draw(data, google.charts.Bar.convertOptions(options));
It looks like; [2]: https://imgyukle.com/i/2.xE348 "nothing working"
Can someone please help me what is wrong with that?
when you draw the chart without --> google.charts.Bar.convertOptions,
the chart ignores the options for --> vAxis.viewWindow.min & max,
so the chart draws fine...
google.charts.load('current', {
packages:['bar']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Date', 'Reading', 'Writing', 'Reading & Writing', 'Math', 'Total'],
['07.08.2018', 220, 230, 450, 610, 1060]
]);
var min = -1;
var max = -1;
var options = {
title: 'Min: ' + min +' Max: ' + max ,
bars:'vertical',
bar: {groupWidth: "25%"},
height: 400,
vAxis: {
format: 'decimal',
minValue: min,
maxValue: max,
viewWindowMode : 'explicit',
viewWindow: {
max:max,
min:min
}
}
};
var chart = new google.charts.Bar(document.getElementById('chart_div'));
chart.draw(data, (options));
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
when you draw the chart with --> google.charts.Bar.convertOptions,
it uses the min & max options, but according to the picture,
min & max are both set to --> -1,
there are no rows that meet this criteria,
so the chart is blank...
google.charts.load('current', {
packages:['bar']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Date', 'Reading', 'Writing', 'Reading & Writing', 'Math', 'Total'],
['07.08.2018', 220, 230, 450, 610, 1060]
]);
var min = -1;
var max = -1;
var options = {
title: 'Min: ' + min +' Max: ' + max ,
bars:'vertical',
bar: {groupWidth: "25%"},
height: 400,
vAxis: {
format: 'decimal',
minValue: min,
maxValue: max,
viewWindowMode : 'explicit',
viewWindow: {
max:max,
min:min
}
}
};
var chart = new google.charts.Bar(document.getElementById('chart_div'));
chart.draw(data, google.charts.Bar.convertOptions(options));
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
note: there are several options that are not supported by Material charts.
see --> Tracking Issue for Material Chart Feature Parity
this includes --> vAxis.minValue, vAxis.maxValue, & vAxis.format
but vAxis.viewWindow.min & max work, and is the same as vAxis.minValue & vAxis.maxValue
to format the y-axis, use --> vAxes (with an e) -- format each axis separately, here you only have one
vAxes: {
0: {
format: 'decimal'
}
}
see following working snippet...
google.charts.load('current', {
packages:['bar']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Date', 'Reading', 'Writing', 'Reading & Writing', 'Math', 'Total'],
['07.08.2018', 220, 230, 450, 610, 1060]
]);
var min = 0;
var max = 1200;
var options = {
title: 'Min: ' + min +' Max: ' + max ,
bars:'vertical',
bar: {groupWidth: "25%"},
height: 400,
vAxis: {
viewWindow: {
max:max,
min:min
}
},
vAxes: {
0: {
format: 'decimal'
}
}
};
var chart = new google.charts.Bar(document.getElementById('chart_div'));
chart.draw(data, google.charts.Bar.convertOptions(options));
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
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>
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>
Hey to all i have the code below for a google pie chart that takes data from a jsontable and i want when i click a slice to redraw the chart based on the selection.
I have the code below and i'm at a loss how to proceed
<head>
<style>
div.absolute {
position: absolute;
top: 120px;
}
</style>
<link href="style.css" rel="stylesheet" />
<!--Auto refresh code -->
<meta http-equiv="refresh" content="<?php echo $sec?>;URL='<?php echo $page?>'">
<!--Load the Ajax API-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://www.google.com/jsapi"></script>
<script src="http://www.google.com/jsapi?ext.js"></script>
<script src="https://rawgit.com/louisremi/jquery-smartresize/master/jquery.throttledresize.js"></script>
<script>
google.load('visualization', '1', {'packages':['corechart']});
google.setOnLoadCallback(initChart);
$(window).on("throttledresize", function (event) {
initChart();
});
function initChart() {
var options = {
title: 'Arrived Today (Email)',
width: '100%',
height: '100%',
sliceVisibilityThreshold: 0,
pieSliceText: 'percentage',
pieStartAngle: 100,
//is3D: 'true',
pieHole: 0.3,
slices: {
1: {offset: 0.2},
2: {offset: 0.3},
3: {offset: 0.4},
4: {offset: 0.5},
5: {offset: 0.6},
},
//slices: {0: {color: 'green'}, 1: {color: 'blue'}},
pieSliceBorderColor: 'black',
legend: 'right',
legendTextStyle: {fontSize: 15},
pieSliceText: 'value' ,
titleTextStyle: {
color: '333333',
fontName: 'Arial',
fontSize: 14 ,
align:'right'
},
chartArea : { left: 35 }
};
var data = new google.visualization.DataTable(<?=$jsonTable?>);
var data2 = new google.visualization.DataTable(<?=$jsonTable2?>);
var total = google.visualization.data.group(data,
[{
type: 'boolean',
column: 0,
modifier: function () {return true;}
}],
[{
type: 'number',
column: 1,
aggregation: google.visualization.data.sum
}]
);
document.getElementById("demo").innerHTML =total.getValue(0,1);
data.addRow(['Total: ' + total.getValue(0, 1), 0]);
drawChart(data, options)
}
function drawChart(data, options) {
var chart = new google.visualization.PieChart(document.getElementById('chart'));
chart.draw(data, options);
google.visualization.events.addListener(chart, 'select', selectHandler);
var label1 = data.pieSliceText('label');
// The selection handler.
// Loop through all items in the selection and concatenate
// a single message from all of them.
function selectHandler() {
var selection = chart.getSelection();
if (selection.length) {
var pieSliceLabel = data.getValue(selection[0].row, 0);
if (pieSliceLabel = 'External')
chart.draw(data2, options);
}
}
}
</script>
</head>
<body>
<h2 align="right"><font size="5">emails Arrived Today</font>
<div id="demo"></div>
</h2>
<div id="chart"></div>
</body>
thanks in advance for any help :)
function initChart() {
....
var data = new google.visualization.DataTable(<?=$jsonTable?>);
var data2 = new google.visualization.DataTable(<?=$jsonTable2?>);
....
}
function drawChart(data, options) {
google.visualization.events.addListener(chart, 'select', selectHandler);
function selectHandler() {
var selection = chart.getSelection();
if (selection.length) {
var pieSliceLabel = data.getValue(selection[0].row, 0);
if (pieSliceLabel = 'External')
chart.draw(data2, options);
}
}
}
Everything looks fine, except the scope of your variable data2.
You initiate it in your function initChart(), and then try to use it in a sub-function from drawChart().
Either you define your var data2 outside any javascript functions, or you pass it as a parameter when you call drawChart.