Google Charts Data View set columns dynamically - javascript

I am using google charts to render the data on webpages. I am using a CSV as an input and that data is then manipulated for google chart api to use.
I want to show the column value on the top of the Bar/Column chart. I figured out that if you create a Data View and do view.setColumns and specify the role annotation then number becomes visible on the top of the chart, otherwise you need to hover on the chart to see the exact value.
My problem is that i am unable to dynamically set the columns and roles to the view. As the input is csv, i will never be sure about the columns.
Main intent is to show the numbers on the bars, if there is any other alternative by which it can be done, then it will be appreciated as well. Cheers
var arrayData = csvAttr.toArrays(csvString, {
onParseValue : csvAttr.hooks.castToScalar
});
var data = new google.visualization.arrayToDataTable(arrayData);
view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{ calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation" },
2,
{ calc: "stringify",
sourceColumn: 2,
type: "string",
role: "annotation" },
3,
{ calc: "stringify",
sourceColumn: 3,
type: "string",
role: "annotation" }
]);

Simple way for set columns dynamically.
var totalColumns = 3
var view = new google.visualization.DataView(dataTable);
var columns = [];
for (var i = 0; i <= totalColumns ; i++) {
if (i > 0) {
columns.push(i);
columns.push({
calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation"
});
} else {
columns.push(i);
}
}
view.setColumns(columns);

Related

How to show a value in google chart [duplicate]

I need to put labels over my google.chart.Bar (not google.visualization.BarChart) the chart is correctly visualized but only shows values on mouse over the bars,please helpme!.
without mouse over
with mouse over
the data is taked from hidden inputs... here the code :
var data3 = new google.visualization.arrayToDataTable([
['Ambitos', 'Programados', 'Terminados',{ role: 'style' }],
['ex', parseInt(document.getElementById("sumex").value),(parseInt(document.getElementById("sumex").value))-( parseInt(document.getElementById("sumpex").value)),document.getElementById("sumex").value],
['ma', parseInt(document.getElementById("summa").value),(parseInt(document.getElementById("summa").value))-( parseInt(document.getElementById("sumpma").value)),document.getElementById("summa").value],
['mo', parseInt(document.getElementById("summo").value),(parseInt(document.getElementById("summo").value))-( parseInt(document.getElementById("sumpmo").value)),document.getElementById("summo").value],
['re', parseInt(document.getElementById("sumre").value),(parseInt(document.getElementById("sumre").value))-( parseInt(document.getElementById("sumpre").value)),document.getElementById("sumre").value],
['tx', parseInt(document.getElementById("sumtx").value),(parseInt(document.getElementById("sumtx").value))-( parseInt(document.getElementById("sumptx").value)),document.getElementById("sumtx").value]]);
var view3 = new google.visualization.DataView(data3);
view3.setColumns([0,1,2,
{ calc: "stringify",
sourceColumn: 3,
type: "string",
role: "annotation" },3]);
var options3 = {
legend: { position: "none" },
chart: {
title: 'Resumen General',
subtitle: 'programados v/s terminados'},
series: {},
axes: { y: {
distance: {label: ''}, } },
chartArea : { width:"95%", height:"80%"} };
var chart3 = new google.charts.Bar(document.getElementById('barras'));
chart3.draw(data3, options3);
p.d. sorry for my bad english!
unfortunately, annotations (bar labels) are not supported on Material charts
recommend using Core chart, with the following option instead...
theme: 'material'
an separate annotation column should be added for each series column,
that should have annotations
when using a DataView to add annotation columns,
be sure to draw the chart using the view (view3),
instead of the original data table (data3)
see following working snippet...
google.charts.load('current', {
callback: function () {
var data3 = new google.visualization.arrayToDataTable([
['Ambitos', 'Programados', 'Terminados',{ role: 'style' }],
['ex', 8,(8)-(6),''],
['ma', 6,(6)-(4),''],
['mo', 4,(4)-(2),''],
['re', 2,(2)-(1),''],
['tx', 1,(1)-(0),'']]);
var view3 = new google.visualization.DataView(data3);
view3.setColumns([0,
1,
{
calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation"
},
2,
{
calc: "stringify",
sourceColumn: 2,
type: "string",
role: "annotation"
},
3
]);
var options3 = {
legend: { position: "none" },
chart: {
title: 'Resumen General',
subtitle: 'programados v/s terminados'
},
series: {},
axes: {
y: {
distance: {label: ''},
}
},
chartArea : {
width:"95%",
height:"80%"
},
theme: 'material'
};
var chart3 = new google.visualization.ColumnChart(document.getElementById('barras'));
chart3.draw(view3, options3);
},
packages:['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="barras"></div>
note: list of options unavailable to Material --> Tracking Issue for Material Chart Feature Parity

Display unit next to value in column

So i've been learning that I can use annotations in order to display the columns value inside a column.
view.setColumns([0, //The "descr column"
1, //Downlink column
{
calc: "stringify",
sourceColumn: 1, // Create an annotation column with source column "1"
type: "string",
role: "annotation"
}]);
I would like to be able to display a unit after each value in the columns.
For example an % ' sign.
Does anyone know how to do this?
(I use a fiddle from another question here on SO,
Show value of Google column chart)
http://jsfiddle.net/bald1/10ubk6o1/
you can use google's NumberFormat class to format the data before drawing the chart
the 'stringify' calculation formula will use the formatted value by default
the format method on NumberFormat takes two arguments:
1) the data table to be formatted
2) the column index of the column to be formatted
var formatNumber = new google.visualization.NumberFormat({
pattern: '#,##0',
suffix: '%'
});
formatNumber.format(data, 1);
formatNumber.format(data, 2);
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['corechart', 'table']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Descr', 'Downlink', 'Uplink'],
['win7protemplate', 12, 5],
['S60', 14, 5],
['iPad', 3.5, 12]
]);
var formatNumber = new google.visualization.NumberFormat({
pattern: '#,##0',
suffix: '%'
});
formatNumber.format(data, 1);
formatNumber.format(data, 2);
var view = new google.visualization.DataView(data);
view.setColumns([0, //The "descr column"
1, //Downlink column
{
calc: "stringify",
sourceColumn: 1, // Create an annotation column with source column "1"
type: "string",
role: "annotation"
},
2, // Uplink column
{
calc: "stringify",
sourceColumn: 2, // Create an annotation column with source column "2"
type: "string",
role: "annotation"
}]);
var columnWrapper = new google.visualization.ChartWrapper({
chartType: 'ColumnChart',
containerId: 'chart_div',
dataTable: view
});
columnWrapper.draw();
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
note: I realize the example provided is from another question but just so you know...
recommend not using jsapi to load the library, according to release notes...
The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader (loader.js) from now on.
<script src="https://www.gstatic.com/charts/loader.js"></script>
this will also change the load statement to...
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});

Google Column Chart with two columns

How to approach a column chart when having month and year.
My data is in this format
['Group','Count','Month','Year'],
['A',10,'February',2015],
['B',8,'February',2015],
['C',15,'February',2016]
Aim is to create a column chart which has X-axis as Month and Y-axis as Count. Now X-axis should have Count for years grouped by month.
Something like this -
I tried to simply pass the above data to see what I can get, but I get error.
Any way to assign Axis the values based on year grouped by month ?
JsFiddle of Google Chart Example
just need three columns, something like this...
['Month', '2015', '2016'],
['Jan', 10, 15],
['Feb', 12, 18],
['Mar', 14, 21],
['Apr', 16, 24]
then you can use a DataView to add the annotations, via calculated columns...
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: 'stringify',
sourceColumn: 1,
type: 'string',
role: 'annotation'
}, 2, {
calc: 'stringify',
sourceColumn: 2,
type: 'string',
role: 'annotation'
}]);
see following working snippet...
google.charts.load('current', {
callback: function () {
var data = google.visualization.arrayToDataTable([
['Month', '2015', '2016'],
['Jan', 10, 15],
['Feb', 12, 18],
['Mar', 14, 21],
['Apr', 16, 24]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: 'stringify',
sourceColumn: 1,
type: 'string',
role: 'annotation'
}, 2, {
calc: 'stringify',
sourceColumn: 2,
type: 'string',
role: 'annotation'
}]);
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(view, {});
},
packages: ['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
EDIT
all google charts require a specific DataFormat
meaning, manipulation is required if your data does not already exist in this format
the visualization library does offer some Data Manipulation Methods, such as group()
which could be used to transform the data into the required format
1) group the data by Month and Year
2) create a new DataTable with the Month column
3) add a column for each Year from the grouped table
4) add the rows for each month
see following working snippet, using the data from the question...
google.charts.load('current', {
callback: function () {
var data = google.visualization.arrayToDataTable([
['Group', 'Count', 'Month', 'Year'],
['A', 10, 'February', 2015],
['B', 8, 'February', 2015],
['C' , 15, 'February', 2016]
]);
// group by month / year
var dataGroup = google.visualization.data.group(
data,
[2, 3],
[{column: 1, aggregation: google.visualization.data.sum, type: 'number', label: 'Count'}]
);
dataGroup.sort([{column: 0},{column: 1}]);
// build final data table
var yearData = new google.visualization.DataTable({
cols: [
{label: 'Month', type: 'string'}
]
});
// add column for each year
var years = dataGroup.getDistinctValues(1);
for (var i = 0; i < years.length; i++) {
yearData.addColumn(
{label: years[i], type: 'number'}
);
}
// add row for each month
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 = yearData.addRow();
yearData.setValue(rowIndex, 0, rowMonth);
}
for (var x = 1; x < yearData.getNumberOfColumns(); x++) {
if (yearData.getColumnLabel(x) === dataGroup.getValue(i, 1).toString()) {
yearData.setValue(rowIndex, x, dataGroup.getValue(i, 2));
}
}
}
var view = new google.visualization.DataView(yearData);
view.setColumns([0, 1, {
calc: 'stringify',
sourceColumn: 1,
type: 'string',
role: 'annotation'
}, 2, {
calc: 'stringify',
sourceColumn: 2,
type: 'string',
role: 'annotation'
}]);
var container = document.getElementById('chart_div');
var chart = new google.visualization.ColumnChart(container);
chart.draw(view);
},
packages: ['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Google Charts API: Always show the Data Point Values using arrayToDataTable. How?

First I'd like to let it be known that although there is a similar question labeled:
Google Charts API: Always show the Data Point Values in Graph
...on the site, I can't seem to use it's solution since my chart is fed using arrayToDataTable.
Here's my code:
function drawChart1998() {
var data = google.visualization.arrayToDataTable([
['Year', 'Index Trend'],
['1/3', 1236777],
['1/7', 834427],
['1/10', 2164890],
['1/14', 1893574],
['1/17', 2851881],
['1/21', 359504],
['1/24', 2264047],
['1/28', 3857933],
['1/31', 2197402],
['2/4', 2469935],
['2/7', 1651752],
['2/11', 4710582],
['2/14', 1565803],
['2/18', 345499],
['2/21', 2817319],
['2/25', 733242],
['2/28', 1485788],
['3/4', 1091181],
['3/7', 4477498],
['3/11', 490931],
['3/14', 3905556],
['3/18', 475417],
['3/21', 1512729],
['3/25', 1782796],
['3/28', 4778434]
]);
var options = {
curveType: "function",
title: '1998 Results',
vAxis: {viewWindow: {min: 0, max: 5006386}},
hAxis: {textStyle: {color: 'black', fontName: 'verdana', fontSize: 10} },
series: {0: { pointSize: 6 }}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_1998'));
chart.draw(data, options);
}
As you can see, I managed to set the series to display the DataPoint dots but I can't seem to figure out how to incorporate the following line of code as the previous post on the site suggests in order to display the values for each DataPoint.
data.addColumn({type: 'string', role: 'annotation'});
For reference, you can input an annotation column to your DataTable using the arrayToDataTable method. Pass an object instead of a string for the column header:
var data = google.visualization.arrayToDataTable([
[/* column headers */, {type: 'string', role: 'annotation'}, /* column headers */],
// ...
]);
This works for any column role.
If you just want to display the value of a data point, you don't have to add an extra column to your DataTable. You can use a DataView to add an "annotation" column, calculated as the string-value of a source column:
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
type: 'string',
role: 'annotation',
sourceColumn: 1,
calc: 'stringify'
}]);
Then draw the chart using the view instead of the DataTable:
chart.draw(view, options);

Customizing Google Charts to display text/number in charts

I am using Google API for generating graphs.
My current Output is :
I want to display text/number in the bar as like below.. I could not find /missing the options to do it. Please let me know... Please do not say it not possible as it is 3rd party API. Its possible as they have done it for other Bar Charts... Link Here
Here is my code.
//Bar Chart
var data_bar = google.visualization.arrayToDataTable([
['Unit Tested','Passed', 'Failed', 'NA' ],
['BTEQ', 100, 20, 3, ]
]);
var options_bar = {
width: 400,
height: 75,
legend: { position: 'top', maxLines: 3 },
bar: { groupWidth: '75%' },
isStacked: true,
series: [{color: '#32B232',visibleInLegend: false}, {color: 'red',visibleInLegend: false}, {color: '#FFD732',visibleInLegend: false}]
};
var chart_bar = new google.visualization.BarChart(document.getElementById('chart_div'));
chart_bar.draw(data_bar, options_bar);
//end of bar chart..
You've actually mentioned the link to the solution yourself:
https://developers.google.com/chart/interactive/docs/gallery/barchart#Labels
Basically you need to add the following code similar to the DataView() mentioned in the link above, but now for every column of the data.
var view = new google.visualization.DataView(data_bar);
view.setColumns([0, 1,
{ calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation" },
2,
{ calc: "stringify",
sourceColumn: 2,
type: "string",
role: "annotation" },
3,
{ calc: "stringify",
sourceColumn: 3,
type: "string",
role: "annotation" }
]);
Edit: to answer your question: the 0,1,2,3 refer to the columns of the data. In order for the annotation to appear the data from the columns (sourceColumn: 1), is transformed to a string with JSON function stringify() (calc: "stringify"). Note that with setColumns() you can use the data multiple times. [0,1,1,1,2,3] would mean that 100 is used three times in the DataView(). Here every column is used once to see the bar and the second time it is transformed to a string and used as annotation.
Your own solutions, although shorter code is more of a hack. Since you enter the data twice. This becomes a problem when you import the data from an external source.
Here is my working answer...
var data_bar = google.visualization.arrayToDataTable([
['Unit Tested','Passed',{ role: 'annotation' }, 'Failed',{ role: 'annotation' }, 'NA',{ role: 'annotation' } ],
['BTEQ', 100,'100', 20,'20', 3,'3' ]

Categories

Resources