Display unit next to value in column - javascript

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']
});

Related

Add new column in google DataView dynamically

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>

Javascript json data read problem for double quote

I'm passing json data to javascript of Google Chart.
My json data format is
["Md. Aslam",170972.7,"gold"]
But in google chart javascript shows like
["JIANGSU LTD",170972.7,"gold"]
Here is showing " in respect of "
I need this data with " as I have given. How do I solve this?
My Controller (sending from data):
def data1 = table.executeQuery("select name, point from table") as JSON
render(view: "/report", model: [data1: data1])
My report.gsp (view of google chart):
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawVisualization);
function drawVisualization() {
google.charts.load("current", {packages:['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
[ 'Element', "Density", { role: "style" } ],
${data1}
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{ calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation" },
2]);
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.ColumnChart(document.getElementById("ord_variation"));
chart.draw(view, options);
}}
</script>
I'm using groovy/grails 3
Finally I got my solution as report.gsp
<g:applyCodec encodeAs="none">
${data1};
</g:applyCodec>
Change your code like below:
<script type="text/javascript">
var j = "${data}"; // data is your json data came from controller
var result = JSON.parse((j.split(""").join('"')).split("=").join(':')); //use result object
</script>
Hope this will helps you

Moving annotations on Bar Chart with Negative Values Google Chart

I am using google charts within an MVC project.
I am looking to implement a bar chart that has negative values.
I would like the annotations on the negative portion of the chart to be on the same side as the end of the bar (just like the positive, see image below, green box is where I would like annotations to be).
I cant seem to find any documentation on how this can be achieved.
Is it possible to move the annotation to the other side?
there are no standard config options that will move the annotations
but you can move them manually
however, the chart will actually move them back whenever activity occurs,
such as on bar hover
have to use a MutationObserver, or something, to keep them there
use chart methods --> getChartLayoutInterface().getXLocation(value)
to find the location
also, need to adjust the axis window to leave room for the labels
see following working snippet...
google.charts.load('current', {
callback: function () {
var data = new google.visualization.DataTable({
cols: [
{label: 'x', type: 'string'},
{label: 'y0', type: 'number'},
],
rows: [
{c:[{v: 'Omega'}, {v: -0.95}]},
{c:[{v: 'Large'}, {v: -0.92}]},
{c:[{v: 'Medium'}, {v: 2.76}]},
{c:[{v: 'Tiny'}, {v: 2.03}]}
]
});
var options = {
annotations: {
alwaysOutside: true,
stem: {
color: 'transparent'
},
textStyle: {
color: '#000000'
}
},
hAxis: {
// leave room for annotation
viewWindow: {
min: data.getColumnRange(1).min - 1
}
},
legend: {
position: 'none'
}
};
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: 'stringify',
sourceColumn: 1,
type: 'string',
role: 'annotation'
}]);
var container = document.getElementById('chart');
var chart = new google.visualization.BarChart(container);
// move annotations
var observer = new MutationObserver(function () {
$.each($('text[text-anchor="start"]'), function (index, label) {
var labelValue = parseFloat($(label).text());
// only negative -- and -- not on tooltip
if ((labelValue < 0) && ($(label).attr('font-weight') !== 'bold')) {
var bounds = label.getBBox();
var chartLayout = chart.getChartLayoutInterface();
$(label).attr('x', chartLayout.getXLocation(labelValue) - bounds.width - 8);
}
});
});
observer.observe(container, {
childList: true,
subtree: true
});
chart.draw(view, options);
},
packages: ['corechart']
});
<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="chart"></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