Google Charts: Remove default Sort for x-axis - charts

Is there a way to remove the default sort for the x-axis? It automatically sorts from A-Z but I want to have it as January - December.
Chart Image :
For the missing months for each year and product type, I've auto generated them in PHP(where my final code is). So it would look like:
["January",0,"Apitong","2018","Analog"],["January",0,"Apitong","2018","Digital"],["January",0,"Apitong","2018","Internet"],["February",0,"Apitong","2018","Analog"],["February",0,"Apitong","2018","Digital"], .. etc
My Sample Code: JSFiddle
google.charts.load('current', {
callback: function() {
var data = google.visualization.arrayToDataTable([
['Month', 'Amount', 'Area', 'Year', 'Product Type'],
['January', 3300, 'Apitong', 2015, 'Analog'],
['February', 1000, 'Apitong', 2015, 'Analog'],
['March', 2000, 'Apitong', 2015, 'Analog'],
]);
google.visualization.events.addListener(product, 'ready', drawChart);
function drawChart() {
var areaData = new google.visualization.DataView(area.getDataTable());
var filters = [{
column: 2,
value: area.getState().selectedValues[0]
}
];
// group by 'Group' / 'Year'
var dataGroup = google.visualization.data.group(
areaData, [0, 3], [{
column: 1,
aggregation: google.visualization.data.sum,
type: 'number',
label: 'Sum'
}, {
column: 1,
aggregation: google.visualization.data.count,
type: 'number',
label: 'Count'
}]
);
dataGroup.sort([{
column: 0
}, {
column: 1
}]);
var ColumnChart = new google.visualization.ChartWrapper({
'chartType': 'ColumnChart',
'containerId': 'productssold_chart_div',
'dataTable': view
});
ColumnChart.draw();
}
},
packages: ['controls', 'corechart']
});

when using a Discrete axis ('string' values),
the axis will sort by the order of the rows in the data table
in this case, the rows are set to alphabetical as a result of using static method --> data.group
to correct this issue, an array of month names is used to build a custom sort order
a new column is added to finalData and the index from the array is used as the order
// build final data table
var monthOrder = [
'January', 'February', 'March',
'April', 'May', 'June',
'July', 'August', 'September',
'October', 'November', 'December'
];
var finalData = new google.visualization.DataTable({
cols: [{
label: 'Group',
type: 'string'
}, {
label: 'Amount',
type: 'number'
}, {
label: 'Count',
type: 'number'
}, {
label: 'Sort',
type: 'number'
}]
});
// add row for each month AMOUNT | COUNT
var rowMonth = null;
var rowIndex = null;
for (var i = 0; i < dataGroup.getNumberOfRows(); i++) {
if (rowMonth !== dataGroup.getValue(i, 0)) {
rowMonth = dataGroup.getValue(i, 0);
rowIndex = finalData.addRow();
finalData.setValue(rowIndex, 0, rowMonth);
}
for (var x = 1; x < finalData.getNumberOfColumns(); x++) {
switch (finalData.getColumnLabel(x)) {
case 'Amount':
finalData.setValue(rowIndex, x, dataGroup.getValue(i, 2).toString());
break;
case 'Count':
finalData.setValue(rowIndex, x, dataGroup.getValue(i, 3).toString());
break;
case 'Sort':
finalData.setValue(rowIndex, x, monthOrder.indexOf(rowMonth));
break;
}
}
}
finalData.sort([{column: 3}]);
see following working snippet...
google.charts.load('current', {
callback: function() {
var data = google.visualization.arrayToDataTable([
['Month', 'Amount', 'Area', 'Year', 'Product Type'],
['February', 1000, 'Apitong', 2015, 'Analog'],
['February', 1700, 'Apitong', 2015, 'Internet'],
['February', 1200, 'Avenida Veteranos', 2015, 'Digital'],
['February', 2800, 'Brgy. Baras', 2015, 'Internet'],
['February', 2150, 'Avenida Veteranos', 2018, 'Digital'],
['February', 2700, 'Apitong', 2018, 'Internet'],
['February', 2500, 'Brgy. Baras', 2018, 'Internet'],
['March', 2000, 'Apitong', 2015, 'Digital'],
['March', 2400, 'Avenida Veteranos', 2015, 'Digital'],
['March', 1600, 'Brgy. Baras', 2015, 'Internet'],
['March', 3000, 'Avenida Veteranos', 2018, 'Analog'],
['March', 1400, 'Apitong', 2018, 'Digital'],
['January', 3300, 'Avenida Veteranos', 2015, 'Analog'],
['March', 2000, 'Brgy. Baras', 2018, 'Analog'],
['January', 2600, 'Brgy. Baras', 2015, 'Internet'],
['January', 1800, 'Apitong', 2015, 'Digital'],
['January', 2100, 'Brgy. Baras', 2015, 'Analog']
]);
var area = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'filter_productssold_area_div',
'dataTable': data,
'options': {
'filterColumnLabel': 'Area',
'ui': {
'allowTyping': false,
'allowMultiple': false,
'allowNone': false,
'sortValues': false,
'label': 'Choose Area',
}
}
});
var year = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'filter_productssold_year_div',
'dataTable': data,
'options': {
'filterColumnLabel': 'Year',
'ui': {
'allowTyping': false,
'allowMultiple': false,
'allowNone': false,
'sortValues': false,
'label': 'Choose Year',
}
}
});
var product = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'filter_productssold_product_div',
'dataTable': data,
'options': {
'filterColumnLabel': 'Product Type',
'ui': {
'allowTyping': false,
'allowMultiple': true,
'allowNone': true,
'sortValues': false,
'label': 'Choose Product',
}
}
});
google.visualization.events.addListener(area, 'ready', drawChart);
google.visualization.events.addListener(area, 'statechange', drawChart);
google.visualization.events.addListener(year, 'ready', drawChart);
google.visualization.events.addListener(year, 'statechange', drawChart);
google.visualization.events.addListener(product, 'ready', drawChart);
google.visualization.events.addListener(product, 'statechange', drawChart);
function drawChart() {
var areaData = new google.visualization.DataView(area.getDataTable());
var filters = [{
column: 2,
value: area.getState().selectedValues[0]
}
];
var selectedYear = year.getState().selectedValues;
if (typeof selectedYear !== 'undefined' && selectedYear.length > 0) {
filters.push({
column: 3,
test: function(value, row, column, table) {
return (selectedYear.indexOf(table.getValue(row, column)) > -1);
}
});
}
var selectedProducts = product.getState().selectedValues;
if (typeof selectedProducts !== 'undefined' && selectedProducts.length > 0) {
filters.push({
column: 4,
test: function(value, row, column, table) {
return (selectedProducts.indexOf(table.getValue(row, column)) > -1);
}
});
}
areaData.setRows(areaData.getFilteredRows(filters));
// group by 'Group' / 'Year'
var dataGroup = google.visualization.data.group(
areaData, [0, 3], [{
column: 1,
aggregation: google.visualization.data.sum,
type: 'number',
label: 'Sum'
}, {
column: 1,
aggregation: google.visualization.data.count,
type: 'number',
label: 'Count'
}]
);
dataGroup.sort([{
column: 0
}, {
column: 1
}]);
// build final data table
var monthOrder = [
'January', 'February', 'March',
'April', 'May', 'June',
'July', 'August', 'September',
'October', 'November', 'December'
];
var finalData = new google.visualization.DataTable({
cols: [{
label: 'Group',
type: 'string'
}, {
label: 'Amount',
type: 'number'
}, {
label: 'Count',
type: 'number'
}, {
label: 'Sort',
type: 'number'
}]
});
// add row for each month AMOUNT | COUNT
var rowMonth = null;
var rowIndex = null;
for (var i = 0; i < dataGroup.getNumberOfRows(); i++) {
if (rowMonth !== dataGroup.getValue(i, 0)) {
rowMonth = dataGroup.getValue(i, 0);
rowIndex = finalData.addRow();
finalData.setValue(rowIndex, 0, rowMonth);
}
for (var x = 1; x < finalData.getNumberOfColumns(); x++) {
switch (finalData.getColumnLabel(x)) {
case 'Amount':
finalData.setValue(rowIndex, x, dataGroup.getValue(i, 2).toString());
break;
case 'Count':
finalData.setValue(rowIndex, x, dataGroup.getValue(i, 3).toString());
break;
case 'Sort':
finalData.setValue(rowIndex, x, monthOrder.indexOf(rowMonth));
break;
}
}
}
finalData.sort([{column: 3}]);
var view = new google.visualization.DataView(finalData);
view.setColumns([0, 1, {
calc: 'stringify',
sourceColumn: 1,
type: 'string',
role: 'annotation'
}, 2, {
calc: 'stringify',
sourceColumn: 2,
type: 'string',
role: 'annotation'
}]);
var ColumnChart = new google.visualization.ChartWrapper({
'chartType': 'ColumnChart',
'containerId': 'productssold_chart_div',
'dataTable': view
});
ColumnChart.draw();
}
area.draw();
year.draw();
product.draw();
},
packages: ['controls', 'corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="filter_productssold_area_div"></div>
<div id="filter_productssold_year_div"></div>
<div id="filter_productssold_product_div"></div>
<div id="productssold_chart_div"></div>

Related

Google charts show unformatted value in tooltip

I have a formatted label displayed on the bars on my chart.
This value also gets formatted in the tooltip. Is there a way to show the unformatted, raw value on the tooltip, while keeping it formatted on the label?
https://jsfiddle.net/67u052kL/1/
var formatter = new google.visualization.NumberFormat({
pattern: 'short'
});
formatter.format(data, 1);
formatter.format(data, 3);
only format the annotation value.
to accomplish, use a custom function for the annotation role, instead of the 'stringify' function.
and you can use the formatter's formatValue method, to format a single value.
view.setColumns([0, 1, {
calc: function (dt, row) {
return formatter.formatValue(dt.getValue(row, 1));
},
type: 'string',
role: 'annotation'
}, 2, 3, {
calc: function (dt, row) {
return formatter.formatValue(dt.getValue(row, 3));
},
type: 'string',
role: 'annotation'
}]);
see following working snippet...
google.charts.load('50', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Team' , 'Actual', { role: 'style'}, 'Target'],
['Alpha' , 35976, 'color: #F6931D', 90000],
['Beta' , 40542, 'color: #FDCB2F', 104167],
['Gamma' , 111227, 'color: #8AC659', 205000],
['Delta' , 238356, 'color: #32A242', 205000],
['Epsilon', 170555, 'color: #3A81C2', 354167]
]);
var formatter = new google.visualization.NumberFormat({
pattern: 'short'
});
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: function (dt, row) {
return formatter.formatValue(dt.getValue(row, 1));
},
type: 'string',
role: 'annotation'
}, 2, 3, {
calc: function (dt, row) {
return formatter.formatValue(dt.getValue(row, 3));
},
type: 'string',
role: 'annotation'
}]);
var options = {
title: {position: 'none'},
orientation: 'vertical',
animation: {duration : 600, startup: 'true', easing:'out'},
annotations: {highContrast: 'true'},
legend: {position: 'none'},
// theme: 'material',
chartArea:{top:5, right: 25, width: '70%', height: '90%'},
hAxis: {format:'short'},
// vAxis: {textPosition:'in'},
// bar: {groupWidth: '90%'},
seriesType: 'bars',
series: {
1: {type: 'bars', color: 'lightgray'}
}
};
var chart = new google.visualization.ComboChart(document.getElementById('chartContentPane'));
chart.draw(view, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chartContentPane"></div>

How to add elements from an array in to echarts tooptip?

suppose I have entity_name = ['www','eee']
I want to add an Entity name into tooltip after the seriesName, which comes from the entity_name array and needs to be added sequentially, one dot for each seriesName and for each Entity name.
I have tried:
formatter: function (obj) {
var value = obj.value;
var a = '';
for(var i = 0; i< 2;i++){
a += '<div>'+ obj.seriesName + entitiy[i]+'</div>'
}
return a;
but all of the entity names are added.
In the tooltip formatter function you can iterate through your entity variables. See example below:
const entityNames = ['www', 'eee'];
var option = {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
tooltip: {
trigger: 'item',
formatter: params => {
const {seriesName, value} = params;
let template = 'Tooltip: <br >';
entityNames.forEach(name => {
template += `${seriesName} ${name} <br />`;
});
return template;
}
},
series: [{
data: [820, 932, 901, 934, 1290, 1330, 1320],
type: 'line',
name: 'mySeries',
}]
};

Google Bar Chart - custom Legend text with total values & column wise total for Table chart

i would like get the total value of Grades in Stacked Bar Graph Legend. picture attached how i wud like to have... for the following working snippet.
and also the Column wise Total for the Table Chart...
i think this can be done with following but how to get it done..
data.setFormattedValue(i, 0, key + ' (' + val + ')');
can have something like this.. when mouseover one location on Bar... need to show all the grades values in single annotation..??
is it possible to have the different values in highlighted places like in below picture? circle B is overall total of Grade1 in graph is correct. and circle A the tooltip total should show for that particular locations total of every Grade's annotation like below.
['Location', 'Company', 'Grade1',{ role: 'annotation' }, 'Grade2',{ role: 'annotation' }, 'Grade3',{ role: 'annotation' }, 'Bal-Grade', 'Total', { role: 'annotation' } ],
google.charts.load('current', {
packages: ['corechart', 'table', 'gauge', 'controls']
}).then(function () {
drawMainDashboard();
});
function drawMainDashboard() {
var dashboard = new google.visualization.Dashboard(
document.getElementById('dashboard_division1'));
var categoryPicker = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'categoryPicker_div',
'options': {
'filterColumnIndex': 1,
'ui': {
'labelStacking': 'vertical',
'label': 'Company Selection:',
'allowTyping': false,
'allowMultiple': false
}
}
});
var categoryPicker1 = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'categoryPicker_div1',
'options': {
'filterColumnIndex': 0,
'ui': {
'labelStacking': 'vertical',
'label': 'Location Selection:',
'allowTyping': false,
'allowMultiple': false
}
}
});
var columnchrt = new google.visualization.ChartWrapper({
'chartType': 'ColumnChart',
'containerId': 'chart_div',
'options': {
title: "Locations charts",
width: 850,
height: 500,
legend: { position: 'top', maxLines: 2 },
bar: { groupWidth: '70%' },
isStacked: true,
focusTarget: 'category',
aggregationTarget: 'category',
explorer: {keepInBounds: true, maxZoomIn: 10.0}
}
});
var table = new google.visualization.ChartWrapper({
'chartType': 'Table',
'containerId': 'table_div',
'options': {
showRowNumber: true,
width: '100%',
height: '100%',
allowHtml: true
},
'view': {'columns': [0,1,2,3,4,5,6]}
});
google.visualization.events.addOneTimeListener(table, 'ready', calcTotals);
function calcTotals() {
// get filtered data table from table chart
var dt = table.getDataTable();
// build aggregation and view columns
var aggColumns = [];
var viewColumns = [0];
for (var i = 2; i < dt.getNumberOfColumns(); i++) {
if (i !== dt.getNumberOfColumns() - 1) {
if (dt.getColumnType(i) === 'number') {
if (dt.getColumnRole(i) !== 'annotation') {
addAggColumn(i);
if (i !== dt.getNumberOfColumns() - 2) {
viewColumns.push(i - 1);
}
}
}
}
}
function addAggColumn(index) {
aggColumns.push({
aggregation: google.visualization.data.sum,
column: index,
label: dt.getColumnLabel(index),
type: dt.getColumnType(index)
});
}
// aggregate data table
var agg = google.visualization.data.group(
dt,
[0],
aggColumns
);
var aggTotal = google.visualization.data.group(
dt,
[{
column: 0,
label: 'Total',
modifier: function (val) {
return 'Total';
},
type: 'string'
}],
aggColumns
);
dt = dt.toDataTable();
dt.addRow(['Total', '--', aggTotal.getValue(0, 1), aggTotal.getValue(0, 2), aggTotal.getValue(0, 3), aggTotal.getValue(0, 4), aggTotal.getValue(0, 5), null]);
table.setDataTable(dt);
table.draw();
viewColumns.push({
calc: function (dt, row) {
var total = 0;
for (var c = 1; c < dt.getNumberOfColumns(); c++) {
if (dt.getColumnLabel(c) !== 'Total') {
total += dt.getValue(row, c);
}
}
return total.toFixed(0);
},
role: 'annotation',
type: 'string'
});
// create agg data view to add annotation
var view = new google.visualization.DataView(agg);
view.setColumns(viewColumns);
view = view.toDataTable();
for (var vc = 0; vc < view.getNumberOfColumns(); vc++) {
var viewLabel = view.getColumnLabel(vc);
for (var ac = 0; ac < agg.getNumberOfColumns(); ac++) {
var aggLabel = agg.getColumnLabel(ac);
if (viewLabel === aggLabel) {
view.setColumnLabel(vc, viewLabel + ' (' + aggTotal.getFormattedValue(0, ac) + ')');
}
}
}
// draw chart
columnchrt.setDataTable(view);
columnchrt.draw();
google.visualization.events.addOneTimeListener(table, 'ready', calcTotals);
}
var data = google.visualization.arrayToDataTable([
['Location', 'Company', 'Grade1', 'Grade2', 'Grade3', 'Bal-Grade', 'Total', { role: 'annotation' } ],
['NYC', 'CUSTOMERS', 0, 0, 13, 5, 19, 29],
['CALI', 'ORG', 270, 210, 0, 32, 51, 60],
['CALI', 'CUSTOMERS', 35.942, 39, 0, 50, 126, 150],
['WDC', 'CUSTOMERS', 0, 0, 35, 52, 88, 100],
['WDC', 'CUSTOMERS', 44.507, 0, 25, 18, 88, 110],
['NJ', 'ORG', 0, 0, 54, 22, 28, 45],
['TXS', 'CUSTOMERS', 0, 0, 0, 10, 11, 20]
]);
dashboard.bind([categoryPicker,categoryPicker1], [table]);
dashboard.draw(data);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="dashboard_division" style="clear:left; display:inline-block; width:100%; float:left; margin-top:5px;">
<div class="float_left panel" style="float:left; width:50%; padding:0px;">
<div id="chart_div"></div>
</div>
<div class="float_left panel" style="width:50%; padding:0px;">
<div class="table_bbar" style="background-color:#27ae60;" >
<div id="categoryPicker_div" style="right:15px; position:absolute;"></div>
<div id="categoryPicker_div1" ></div>
</div>
<div id="table_div"></div>
</div>
</div>
to get the total row for the table chart,
we can use a modifier function in the aggregation.
we aggregate once by location,
then again in total.
the modifier function allows us to return the same value for every row,
thus giving us the total for all rows.
then we can add the results from the total agg to the location agg.
// aggregate data table
var agg = google.visualization.data.group(
dt,
[0],
aggColumns
);
var aggTotal = google.visualization.data.group(
dt,
[{
column: 0,
label: 'Total',
modifier: function (val) {
return 'Total';
},
type: 'string'
}],
aggColumns
);
var rowIndex = agg.addRow();
for (var i = 0; i < agg.getNumberOfColumns(); i++) {
agg.setValue(rowIndex, i, aggTotal.getValue(0, i));
}
then we can use the agg total data table to set the labels in the column chart legend.
// create agg data view to add annotation
var view = new google.visualization.DataView(agg);
view.setColumns(viewColumns);
view = view.toDataTable();
for (var vc = 0; vc < view.getNumberOfColumns(); vc++) {
var viewLabel = view.getColumnLabel(vc);
for (var ac = 0; ac < agg.getNumberOfColumns(); ac++) {
var aggLabel = agg.getColumnLabel(ac);
if (viewLabel === aggLabel) {
view.setColumnLabel(vc, viewLabel + ' (' + aggTotal.getFormattedValue(0, ac) + ')');
}
}
}
one other slight change, since we are re-drawing the charts inside the 'ready' event,
we must use a one time event, else we'll go into an endless loop.
google.visualization.events.addOneTimeListener(table, 'ready', calcTotals);
see following working snippet...
google.charts.load('current', {
packages: ['corechart', 'table', 'gauge', 'controls']
}).then(function () {
drawMainDashboard();
});
function drawMainDashboard() {
var dashboard = new google.visualization.Dashboard(
document.getElementById('dashboard_division1'));
var categoryPicker = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'categoryPicker_div',
'options': {
'filterColumnIndex': 1,
'ui': {
'labelStacking': 'vertical',
'label': 'Company Selection:',
'allowTyping': false,
'allowMultiple': false
}
}
});
var categoryPicker1 = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'categoryPicker_div1',
'options': {
'filterColumnIndex': 0,
'ui': {
'labelStacking': 'vertical',
'label': 'Location Selection:',
'allowTyping': false,
'allowMultiple': false
}
}
});
var columnchrt = new google.visualization.ChartWrapper({
'chartType': 'ColumnChart',
'containerId': 'chart_div',
'options': {
title: "Locations charts",
width: 850,
height: 500,
legend: { position: 'top', maxLines: 2 },
bar: { groupWidth: '70%' },
isStacked: true,
explorer: {keepInBounds: true, maxZoomIn: 10.0}
}
});
var table = new google.visualization.ChartWrapper({
'chartType': 'Table',
'containerId': 'table_div',
'options': {
showRowNumber: true,
width: '100%',
height: '100%',
allowHtml: true
},
'view': {'columns': [0,1,2,3,4,5,6]}
});
google.visualization.events.addOneTimeListener(table, 'ready', calcTotals);
function calcTotals() {
// get filtered data table from table chart
var dt = table.getDataTable();
// build aggregation and view columns
var aggColumns = [];
var viewColumns = [0];
for (var i = 2; i < dt.getNumberOfColumns(); i++) {
if (i !== dt.getNumberOfColumns() - 1) {
if (dt.getColumnType(i) === 'number') {
if (dt.getColumnRole(i) !== 'annotation') {
addAggColumn(i);
if (i !== dt.getNumberOfColumns() - 2) {
viewColumns.push(i - 1);
}
}
}
}
}
function addAggColumn(index) {
aggColumns.push({
aggregation: google.visualization.data.sum,
column: index,
label: dt.getColumnLabel(index),
type: dt.getColumnType(index)
});
}
// aggregate data table
var agg = google.visualization.data.group(
dt,
[0],
aggColumns
);
var aggTotal = google.visualization.data.group(
dt,
[{
column: 0,
label: 'Total',
modifier: function (val) {
return 'Total';
},
type: 'string'
}],
aggColumns
);
dt = dt.toDataTable();
dt.addRow(['Total', '--', aggTotal.getValue(0, 1), aggTotal.getValue(0, 2), aggTotal.getValue(0, 3), aggTotal.getValue(0, 4), aggTotal.getValue(0, 5), null]);
table.setDataTable(dt);
table.draw();
viewColumns.push({
calc: function (dt, row) {
var total = 0;
for (var c = 1; c < dt.getNumberOfColumns(); c++) {
if (dt.getColumnLabel(c) !== 'Total') {
total += dt.getValue(row, c);
}
}
return total.toFixed(0);
},
role: 'annotation',
type: 'string'
});
// create agg data view to add annotation
var view = new google.visualization.DataView(agg);
view.setColumns(viewColumns);
view = view.toDataTable();
for (var vc = 0; vc < view.getNumberOfColumns(); vc++) {
var viewLabel = view.getColumnLabel(vc);
for (var ac = 0; ac < agg.getNumberOfColumns(); ac++) {
var aggLabel = agg.getColumnLabel(ac);
if (viewLabel === aggLabel) {
view.setColumnLabel(vc, viewLabel + ' (' + aggTotal.getFormattedValue(0, ac) + ')');
}
}
}
// draw chart
columnchrt.setDataTable(view);
columnchrt.draw();
google.visualization.events.addOneTimeListener(table, 'ready', calcTotals);
}
var data = google.visualization.arrayToDataTable([
['Location', 'Company', 'Grade1', 'Grade2', 'Grade3', 'Bal-Grade', 'Total', { role: 'annotation' } ],
['NYC', 'CUSTOMERS', 0, 0, 13, 5, 19, 19],
['CALI', 'ORG', 270, 210, 0, 32, 51, 51],
['CALI', 'CUSTOMERS', 35.942, 39, 0, 50, 126, 126],
['WDC', 'CUSTOMERS', 0, 0, 35, 52, 88, 88],
['WDC', 'CUSTOMERS', 44.507, 0, 25, 18, 88, 88],
['NJ', 'ORG', 0, 0, 54, 22, 28, 28],
['TXS', 'CUSTOMERS', 0, 0, 0, 10, 11, 11]
]);
dashboard.bind([categoryPicker,categoryPicker1], [table]);
dashboard.draw(data);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="dashboard_division" style="clear:left; display:inline-block; width:100%; float:left; margin-top:5px;">
<div class="float_left panel" style="float:left; width:50%; padding:0px;">
<div id="chart_div"></div>
</div>
<div class="float_left panel" style="width:50%; padding:0px;">
<div class="table_bbar" style="background-color:#27ae60;" >
<div id="categoryPicker_div" style="right:15px; position:absolute;"></div>
<div id="categoryPicker_div1" ></div>
</div>
<div id="table_div"></div>
</div>
</div>

Add labels for point in google charts

Does google charts support the ability to add labels to a chart? I need to add labels to the chart, but I don't know how to do it.
I'm using such function for chart draw:
function drawChart(node, rows) {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Index');
data.addRows(rows);
var options = {
titleTextStyle: {
color: '#00FF00',
},
height: 350,
width: $('#' + node).width(),
pointsVisible: true,
colors:['#00FF00'],
backgroundColor: '#1b1b1b',
legend: {position: 'right', textStyle: {color: '#fff', fontSize: 12}},
pointShape: 'square',
annotations: {
textStyle: {
fontName: 'Times-Roman',
fontSize: 18,
bold: true,
italic: true,
color: '#e5d385',
},
stem: {
length: 0
}
},
hAxis: {
title: "Date",
titleTextStyle: {
color: '#fff'
},
format: 'dd.MM.yyyy',
gridlines: {count: 15, color: '#7d7d7d'},
baselineColor: '#fff',
slantedTextAngle: 45,
slantedText: true,
baselineColor: '#fff',
minorGridlines:{
color: "#494949"
},
textStyle:{color: '#FFF'},
ticks: ticksX
},
vAxis: {
title: "Index",
titleTextStyle: {
color: '#fff'
},
gridlines: {color: '#7d7d7d'},
minValue: 0,
baselineColor: '#fff',
minorGridlines:{
color: "#494949"
},
textStyle:{color: '#FFF'},
ticks: ticksY
},
};
var dataView = new google.visualization.DataView(data);
dataView.setColumns([
// reference existing columns by index
0, 1,
// add function for line color
{
calc: function(data, row) {
var colorDown = '#FF0000';
var colorUp = '#00FF00';
if ((row === 0) && (data.getValue(row, 1) < data.getValue(row + 1, 1))) {
return colorDown;
} else if ((row > 0) && (data.getValue(row - 1, 1) < data.getValue(row, 1))) {
return colorDown;
}
return colorUp;
},
type: 'string',
role: 'style',
}
]);
var chart = new google.visualization.LineChart(document.getElementById(node));
chart.draw(dataView, options);
}
I can't find information how to add labels to a chart. All documentation contains information how to add labels to the axes of the chart. I need to add labels above the line chart points.
Can you help me with it?
annotations, or labels, are added using an annotation column role,
similar to the style column role, already being used.
here, I add an annotation column role to the data view,
to display labels for the min & max values...
google.charts.load('current', {
packages:['corechart']
}).then(function () {
var rows = [];
var oneDay = (24 * 60 * 60 * 1000);
var currentEndDate = new Date();
var currentStartDate = new Date(currentEndDate.getTime() - (oneDay * 365.25));
for (var i = currentStartDate.getTime(); i <= currentEndDate.getTime(); i = i + oneDay) {
var direction = (i % 2 === 0) ? 1 : -1;
var rowDate = new Date(i);
rows.push([rowDate, rowDate.getMonth() + (rowDate.getDate() * direction)]);
}
drawChart('chart_div', rows);
});
function drawChart(node, rows) {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Index');
data.addRows(rows);
var options = {
titleTextStyle: {
color: '#00FF00',
},
height: 350,
width: $('#' + node).width(),
pointsVisible: true,
colors:['#00FF00'],
backgroundColor: '#1b1b1b',
legend: {position: 'right', textStyle: {color: '#fff', fontSize: 12}},
pointShape: 'square',
annotations: {
textStyle: {
fontName: 'Times-Roman',
fontSize: 18,
bold: true,
italic: true,
color: '#e5d385',
},
stem: {
length: 0
}
},
hAxis: {
title: "Date",
titleTextStyle: {
color: '#fff'
},
format: 'dd.MM.yyyy',
gridlines: {count: 15, color: '#7d7d7d'},
baselineColor: '#fff',
slantedTextAngle: 45,
slantedText: true,
baselineColor: '#fff',
minorGridlines:{
color: "#494949"
},
textStyle:{color: '#FFF'}
},
vAxis: {
title: "Index",
titleTextStyle: {
color: '#fff'
},
gridlines: {color: '#7d7d7d'},
minValue: 0,
baselineColor: '#fff',
minorGridlines:{
color: "#494949"
},
textStyle:{color: '#FFF'}
},
};
var range = data.getColumnRange(1);
var dataView = new google.visualization.DataView(data);
dataView.setColumns([
// reference existing columns by index
0, 1,
// add function for line color
{
calc: function(data, row) {
var colorDown = '#FF0000';
var colorUp = '#00FF00';
if ((row === 0) && (data.getValue(row, 1) < data.getValue(row + 1, 1))) {
return colorDown;
} else if ((row > 0) && (data.getValue(row - 1, 1) < data.getValue(row, 1))) {
return colorDown;
}
return colorUp;
},
type: 'string',
role: 'style',
},
// add annotation
{
calc: function(data, row) {
var value = data.getValue(row, 1);
if (value === range.min) {
return 'Min: ' + data.getFormattedValue(row, 1);
} else if (value === range.max) {
return 'Max: ' + data.getFormattedValue(row, 1);
}
return null;
},
type: 'string',
role: 'annotation',
}
]);
var chart = new google.visualization.LineChart(document.getElementById(node));
chart.draw(dataView, options);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src='https://www.gstatic.com/charts/loader.js'></script>
<div id="chart_div"></div>

Tooltip number formatting in google chart

How can I format number in a tooltip in google chart? I tried to apply "none" formatting in datatable and also applied "####" formatting on h-axis in google chart option but still can see 2,012 in tooltip.
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
[
{label: "year", type: "number", format: "none"},
{label: "performance", type: "number", format: "none"},
],
["2009", 10],
["2010", 15],
["2011", 3],
["2012", 5]
]);
var options = {
title: 'Company Performance',
hAxis: {title: 'Year', titleTextStyle: {color: '#333'}, format: "####"},
vAxis: {minValue: 0}
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
JSFiddle can be found here:
https://jsfiddle.net/ux37j0dk/3/
by default, the tooltip will display the formatted value of data table cell
you can use the NumberFormat class to format the data table...
var yearPattern = "0";
var formatNumber = new google.visualization.NumberFormat({
pattern: yearPattern
});
formatNumber.format(data, 0);
see following working snippet...
google.charts.load('current', {
'packages': ['corechart']
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
[{
label: "year",
type: "number",
format: "none"
},
{
label: "performance",
type: "number",
format: "none"
},
],
["2009", 10],
["2010", 15],
["2011", 3],
["2012", 5]
]);
var yearPattern = "0";
var formatNumber = new google.visualization.NumberFormat({
pattern: yearPattern
});
formatNumber.format(data, 0);
var options = {
title: 'Company Performance',
hAxis: {
title: 'Year',
titleTextStyle: {
color: '#333'
},
format: yearPattern
},
vAxis: {
minValue: 0
}
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
you can also use object notation to supply both the value (v:) and the formatted value (f:),
when loading the data table...
[{v: "2009", f: "2009"}, 10],
see following working snippet...
google.charts.load('current', {
'packages': ['corechart']
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
[{
label: "year",
type: "number",
format: "none"
},
{
label: "performance",
type: "number",
format: "none"
},
],
[{v: "2009", f: "2009"}, 10],
[{v: "2010", f: "2010"}, 15],
[{v: "2011", f: "2011"}, 3],
[{v: "2012", f: "2012"}, 5]
]);
var yearPattern = "0";
var options = {
title: 'Company Performance',
hAxis: {
title: 'Year',
titleTextStyle: {
color: '#333'
},
format: yearPattern
},
vAxis: {
minValue: 0
}
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>