Add new column in google DataView dynamically - javascript

I'm using google chart datatable getting data from a Json, but I want to add a new column result of divide column 2 by 15000.
Using google.visualization.DataTable()
I'm getting something like this
Colum 1 | Column 2
First row 15.000.000€
Second row 20.000.000€
I want Column 3 like this
Colum 1 | Column 2 | Column 3
First row 15.000.000€ 1.000,00€
Second row 20.000.000€ 1.333,33€

you can use a DataView to add the new column, using a calculated column.
create a data view from the data table
var view = new google.visualization.DataView(data);
then use the setColumns method to change the view columns.
we use the column index of the first two columns,
then use a calculation for the third.
view.setColumns([0, 1, {
calc: function (dt, row) {
return dt.getValue(row, 1) / 15000;
},
label: 'Column 3',
type: 'number'
}]);
see following working snippet...
google.charts.load('current', {
packages: ['table']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Column 1', 'Column 2'],
['First Row', 15000000],
['Second Row', 20000000]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: function (dt, row) {
return dt.getValue(row, 1) / 15000;
},
label: 'Column 3',
type: 'number'
}]);
var table = new google.visualization.Table(document.getElementById('chart_div'));
table.draw(view);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
EDIT
to format the number,
use google's number formatter,
and object notation for the value.
var formatNumber = new google.visualization.NumberFormat({
pattern: '#,##0.00',
suffix: '€'
});
to format a data table column, use the format method.
formatNumber.format(data, 1);
to format a single value, use the formatValue method.
var value = dt.getValue(row, 1) / 15000;
return {
v: value,
f: formatNumber.formatValue(value)
};
see following working snippet..
google.charts.load('current', {
packages: ['table']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Column 1', 'Column 2'],
['First Row', 15000000],
['Second Row', 20000000]
]);
var formatNumber = new google.visualization.NumberFormat({
pattern: '#,##0.00',
suffix: '€'
});
formatNumber.format(data, 1);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: function (dt, row) {
var value = dt.getValue(row, 1) / 15000;
return {
v: value,
f: formatNumber.formatValue(value)
};
},
label: 'Column 3',
type: 'number'
}]);
var table = new google.visualization.Table(document.getElementById('chart_div'));
table.draw(view);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Related

Set colour of google bar chart via role:style

From a dynamically generate data array I am creating a DataTable and want to style it in a google charts as a bar chart.
I am going thru every data entry and creating a label and annotation.
But how do I give the column a certain colour?
I figured out that I need to use the role "style" but could not figure out the right syntax for the colour.
var dataTable = google.visualization.arrayToDataTable(data);
//Formatters
var intergerFormatter = new google.visualization.NumberFormat({
groupingSymbol: ",",
fractionDigits: 0
});
for (var i = 0; i < data[0].length; i++) {
intergerFormatter.format(dataTable, i);
}
var view = new google.visualization.DataView(dataTable);
var cols = [0];
for (var i = 1; i < data[0].length; i++) {
cols.push({
sourceColumn: i,
type: "number",
label: data[0][i]
});
cols.push({
calc: "stringify",
sourceColumn: i,
type: "string",
role: "annotation"
});
cols.push({
//the following options are not working...
role: "style: green"
'color: green'
color: "#109618"
});
}
view.setColumns(cols);
var chart = new google.visualization.ColumnChart(document.getElementById('PTCoverage'));
chart.draw(view, options);
use the calc function to return the value for the calculated column...
cols.push({
calc: function () {
return "green";
},
role: "style",
type: "string"
});
UPDATE
if the bars for every row in a specific column should be the same color,
don't need the 'style' column
use the colors configuration option instead
the colors option takes an array of colors,
one for each column / series
one series...
colors: ["green"]
two series...
colors: ["green", "red"]
etc...
EXAMPLE 1
using colors config option to apply colors to columns...
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['x', 'y0', 'y1', 'y2'],
['Test 1', 500, 600, 1200],
['Test 2', 500, 600, 1200]
]);
var options = {
colors: ['green', 'red', 'blue']
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
EXAMPLE 2
use a 'style' column to change the colors for column / series 1...
(which basically overrides "green")
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['x', 'y0', {role: 'style', type: 'string'}, 'y1', 'y2'],
['Test 1', 500, 'cyan', 600, 1200],
['Test 2', 500, 'magenta', 600, 1200]
]);
var options = {
colors: ['green', 'red', 'blue']
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
I now managed to implement an array which returns a new color for evry bar, see below.
var colors = ['#66cc33','#3366CC','#DC3912','#FF9900','#DD4477','#994499','#0099C6','#109618'];
//...
cols.push({
sourceColumn: i,
calc: function () {
ccount++;
return colors[ccount];
},
role: "style",
type: "string"
});
//...
But this only adds the colors to the data in SR2, SR3 and SR4 have the colors as before, see pic (green color in the left chart, pink color in the midle and right for positive tested)
I think it might be because my data looks like this
var data = [
['Release', 'Test Case missing', 'negative tested', 'untested', 'partially tested','tested with restrictions','part tested with restrictions', 'positive tested'],
['SR2', MS2PTStatusMask.TCmissing,MS2PTStatusMask.NegTested,MS2PTStatusMask.UnTested,MS2PTStatusMask.RestTested,MS2PTStatusMask.PartTestWithRest,MS2PTStatusMask.PartTested,MS2PTStatusMask.PosTested],
['SR3', MS3PTStatusMask.TCmissing,MS3PTStatusMask.NegTested,MS3PTStatusMask.UnTested,MS3PTStatusMask.RestTested,MS3PTStatusMask.PartTestWithRest,MS3PTStatusMask.PartTested,MS3PTStatusMask.PosTested],
['SR4', MS4PTStatusMask.TCmissing,MS4PTStatusMask.NegTested,MS4PTStatusMask.UnTested,MS4PTStatusMask.RestTested,MS4PTStatusMask.PartTestWithRest,MS4PTStatusMask.PartTested,MS4PTStatusMask.PosTested],
]
How do I add the colors to the other bars?

Google Chart - JSON Data Source Item as Legend Field - Stacked Column

I want to create a stacked column chart with a JSON data source and use an item in my JSON data to group by as a field. I haven't found any resources on how to do this, and I have no JS experience.
I know how to join multiple data sources if you know the fields you'll be grouping by. But in this case the Client fields are dynamic.
This stack question is similar to what I want to accomplish: JSON format for Google chart stacked column
My data comes in like the following:
[["2017/06/25", "Some Client A", 805.0], ["2017/07/02", "Some Client B", 955.0], ["2017/07/09", "Some Client C", 805.0]]
So far I have the below. Which obviously doesn't work:
function drawStacked() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Week');
data.addColumn('string', 'client');
data.addColumn('number', 'Hours');
data.addRows( {{ sbl1|safe }} );
the data shown in the post should work fine with the code from the other answer,
see following working snippet...
google.charts.load('current', {
callback: function () {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Week');
data.addColumn('string', 'client');
data.addColumn('number', 'Hours');
data.addRows([["2017/07/09", "Some Client A", 805.0], ["2017/07/09", "Some Client B", 955.0], ["2017/07/09", "Some Client C", 805.0]]);
// create data view
var view = new google.visualization.DataView(data);
// init column arrays
var aggColumns = [];
var viewColumns = [{
calc: function (dt, row) {
return dt.getFormattedValue(row, 0);
},
label: data.getColumnLabel(0),
type: 'string'
}];
// build view & agg column for each client
data.getDistinctValues(1).forEach(function (client, index) {
// add view column
viewColumns.push({
calc: function (dt, row) {
if (dt.getValue(row, 1) === client) {
return dt.getValue(row, 2);
}
return null;
},
label: client,
type: 'number'
});
// add agg column
aggColumns.push({
aggregation: google.visualization.data.sum,
column: index + 1,
label: client,
type: 'number'
});
});
// set view columns
view.setColumns(viewColumns);
// agg view by first column
var group = google.visualization.data.group(
view,
[0],
aggColumns
);
// draw chart
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(group, {
isStacked: true
});
},
packages: ['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

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, how can i set a calculated view in a ChartWrapper?

i use the ChartWrapper from google charts.. my actual implementation looks like this:
var dataTable=new google.visualization.DataTable(DATA);
var options = {
title: 'Name of the Chart',
vAxis: {title: "Cups"},
hAxis: {title: "Month"},
isStacked: false,
pointSize: 3
};
var chartWrapperArgs = {
chartType: "LineChart",
dataTable: dataTable,
view: {"columns":[0,1,2]},
options: options,
containerId: "chart"]
};
var chartWrapper = new google.visualization.ChartWrapper(chartWrapperArgs);
chartWrapper.draw();
the problem is, sometimes i must change the data type from "date" to "string" i do this in my old implementation(there is no ChartWrapper) like this:
var dataView = new google.visualization.DataView(dataTable);
dataView.setColumns([{
type: 'string',
label: dataView.getColumnLabel(0),
calc: function (dt, row) {
return dt.getFormattedValue(row, 0);
}
}, 1]);
this works and now i have tried the same with my ChartWrapper implementation but with no success:
i have tried this two approaches:
1.)
var dataTable=new google.visualization.DataTable(DATA);
var chartWrapperArgs = {
chartType: "LineChart",
dataTable: dataTable,
view: {"columns":[
{
type: 'string',
label: dataTable.getColumnLabel(0),
calc: function (dt, row) {
return dt.getFormattedValue(row, 0);
}
},
1
]},
options: options,
containerId: "chart"]
};
var chartWrapper = new google.visualization.ChartWrapper(chartWrapperArgs);
and my second:
var dataTable=new google.visualization.DataTable(DATA);
var dataView = new google.visualization.DataView(dataTable);
dataView.setColumns([{
type: 'string',
label: dataView.getColumnLabel(0),
calc: function (dt, row) {
return dt.getFormattedValue(row, 0);
}
}, 1]);
var ViewData= dataView.toJSON();
var chartWrapperArgs = {
chartType: "LineChart",
dataTable: dataTable,
view: ViewData,
options: options,
containerId: "chart"]
};
var chartWrapper = new google.visualization.ChartWrapper(chartWrapperArgs);
but this did also not worked..
what do i wrong ?
i know i can set the view directly to the dataTable like "dataTable : view" but i want only do this in the "view:" option or the chartWrapper.setView() option.. or is this not possible ?
Your first method (setting the view parameter) should work, but your code had a syntax error at the end of the containerId: "chart"] line (the ] should not be there):
var chartWrapperArgs = {
chartType: "LineChart",
dataTable: dataTable,
view: {
columns: [{
type: 'string',
label: dataTable.getColumnLabel(0),
calc: function (dt, row) {
return dt.getFormattedValue(row, 0);
}
}, 1]
},
options: options,
containerId: "chart"
};
var chartWrapper = new google.visualization.ChartWrapper(chartWrapperArgs);
If that isn't working, can you post a full example demonstrating the problem?

Categories

Resources