I have a problem to change number format in my google chart.
I checked stackoverflow topic and I found it : http://jsfiddle.net/h5ea6xqu/
My problem is simple, I want exactly the same thing, but it doesn't working.
I have "," instead space for my grouping symbol... If someone have the solution, it would be awesome.
my problem
My code :
function drawChart($id) {
var id=$id;
var kwexist = (id + "_kw_exist");
var kwexistvariable = $("#"+kwexist).html();
var kwled = (id + "_kw_led");
var kwledvariable = $("#"+kwled).html();
var data = google.visualization.arrayToDataTable([
['Element', 'Density', { role: 'style' }, { role: 'annotation' } ],
['Existant kWh', parseFloat(kwexistvariable), '#3B7CC9', parseFloat(kwexistvariable)],
['LED kWh', parseFloat(kwledvariable), '#3B7CC9' , parseFloat(kwledvariable)]
]);
var options = {
};
var numberFormat = new google.visualization.NumberFormat({
groupingSymbol: ' '
})
numberFormat.format(data, 1);
var chart_div = document.getElementById('chart_div_kw');
var chart = new google.visualization.ColumnChart(chart_div);
// Wait for the chart to finish drawing before calling the getImageURI() method.
google.visualization.events.addListener(chart, 'ready', function () {
chart_div.innerHTML = chart.getImageURI();
var testokok = chart.getImageURI();
console.log(chart_div.innerHTML);
});
chart.draw(data, options);
}
not sure i follow the question exactly
but if you want to format the number shown on the bar (annotation)
also format that column...
numberFormat.format(data, 3);
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart($id) {
var data = google.visualization.arrayToDataTable([
['Element', 'Density', { role: 'style' }, { role: 'annotation' } ],
['Existant kWh', parseFloat(10000), '#3B7CC9', parseFloat(10000)],
['LED kWh', parseFloat(15000), '#3B7CC9' , parseFloat(15000)]
]);
var options = {
};
var numberFormat = new google.visualization.NumberFormat({
groupingSymbol: ' '
});
numberFormat.format(data, 1);
numberFormat.format(data, 3);
var chart_div = document.getElementById('chart_div');
var chart = new google.visualization.ColumnChart(chart_div);
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
Related
How can we change default color to 'green' for 'Executed' column and 'red' for 'Not Executed' column below? I tried using series/colors but no luck.
I tried adding color parameter, series in both options and view below. Nothings working.
Code:
<html>
<head>
<title>Google Charts Tutorial</title>
<script type = "text/javascript" src = "https://www.gstatic.com/charts/loader.js">
</script>
<script type = "text/javascript">
google.charts.load('current', {packages: ['corechart']});
</script>
<script language = "JavaScript">
function drawChart(){
// Define the chart to be drawn.
var data = google.visualization.arrayToDataTable([
['Status', 'Outcome', { role: 'style' }],
['Executed', 70,'green'],
['Not Executed', 5,'red']
]);
var groupData = google.visualization.data.group(
data,
[{column: 0, modifier: function () {return 'total'}, type:'string'}],
[{column: 1, aggregation: google.visualization.data.sum, type: 'number'}]
);
var formatPercent = new google.visualization.NumberFormat({
pattern: '#,##0.0%'
});
var formatShort = new google.visualization.NumberFormat({
pattern: 'short'
});
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: function (dt, row) {
var amount = formatShort.formatValue(dt.getValue(row, 1));
var percent = formatPercent.formatValue(dt.getValue(row, 1) / groupData.getValue(0, 1));
return amount + ' (' + percent + ')';
},
type: 'string',
role: 'annotation'
}]);
var options = { title: 'Google charts', 'legend':'none'};
var chart = new google.visualization.ColumnChart(document.getElementById('container1'));
chart.draw(view, options);
}
google.charts.setOnLoadCallback(drawChart);
</script>
</head>
<body>
<table border='1px' cellpadding='5' cellspacing='0' style='border: solid 1px Silver; font-size: x-small;width: 100%'>
<tr align='center' valign='top'>
<td align='center' style='width:100px' valign='center' bgcolor='white'>
<div id="container1" style="width:400; height:280"></div>
</td>
</tr>
</table>
</body>
</html>
All I need to do is to change blue color of bars to green and red. Kindly check and help.
in the data view, need to include the column index for the style role from the data table...
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, 2, { // <-- include column index 2 for style role
calc: function (dt, row) {
var amount = formatShort.formatValue(dt.getValue(row, 1));
var percent = formatPercent.formatValue(dt.getValue(row, 1) / groupData.getValue(0, 1));
return amount + ' (' + percent + ')';
},
type: 'string',
role: 'annotation'
}]);
see following working snippet...
google.charts.load('current', {packages: ['corechart']});
function drawChart(){
// Define the chart to be drawn.
var data = google.visualization.arrayToDataTable([
['Status', 'Outcome', { role: 'style' }],
['Executed', 70,'green'],
['Not Executed', 5,'red']
]);
var groupData = google.visualization.data.group(
data,
[{column: 0, modifier: function () {return 'total'}, type:'string'}],
[{column: 1, aggregation: google.visualization.data.sum, type: 'number'}]
);
var formatPercent = new google.visualization.NumberFormat({
pattern: '#,##0.0%'
});
var formatShort = new google.visualization.NumberFormat({
pattern: 'short'
});
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, 2, {
calc: function (dt, row) {
var amount = formatShort.formatValue(dt.getValue(row, 1));
var percent = formatPercent.formatValue(dt.getValue(row, 1) / groupData.getValue(0, 1));
return amount + ' (' + percent + ')';
},
type: 'string',
role: 'annotation'
}]);
var options = { title: 'Google charts', 'legend':'none'};
var chart = new google.visualization.ColumnChart(document.getElementById('container1'));
chart.draw(view, options);
}
google.charts.setOnLoadCallback(drawChart);
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="container1"></div>
I am using google charts timeline to plot the data below using google charts timeline.
[{"id":59291,"idJob":2,"idOperation":3,"start":0,"end":3,"machine":1}, {"id":59292,"idJob":2,"idOperation":2,"start":3,"end":7,"machine":1},{"id":59293,"idJob":1,"idOperation":1,"start":7,"end":8,"machine":1},{"id":59294,"idJob":2,"idOperation":1,"start":8,"end":11,"machine":1},{"id":59295,"idJob":1,"idOperation":2,"start":0,"end":1,"machine":2},{"id":59296,"idJob":2,"idOperation":5,"start":7,"end":14,"machine":3},{"id":59297,"idJob":1,"idOperation":4,"start":1,"end":10,"machine":4},{"id":59298,"idJob":1,"idOperation":3,"start":8,"end":21,"machine":5},{"id":59299,"idJob":2,"idOperation":6,"start":3,"end":10,"machine":6},{"id":59300,"idJob":2,"idOperation":4,"start":11,"end":14,"machine":6},{"id":59301,"idJob":2,"idOperation":9,"start":10,"end":13,"machine":7},{"id":59302,"idJob":1,"idOperation":6,"start":13,"end":14,"machine":7},{"id":59303,"idJob":2,"idOperation":8,"start":14,"end":16,"machine":7},{"id":59304,"idJob":2,"idOperation":7,"start":16,"end":21,"machine":7},{"id":59305,"idJob":1,"idOperation":5,"start":21,"end":23,"machine":7},{"id":59306,"idJob":1,"idOperation":9,"start":14,"end":17,"machine":8},{"id":59307,"idJob":2,"idOperation":12,"start":18,"end":21,"machine":8},{"id":59308,"idJob":2,"idOperation":10,"start":21,"end":26,"machine":8},{"id":59309,"idJob":1,"idOperation":8,"start":26,"end":28,"machine":8},{"id":59310,"idJob":2,"idOperation":11,"start":18,"end":24,"machine":9},{"id":59311,"idJob":1,"idOperation":7,"start":24,"end":27,"machine":9},{"id":59312,"idJob":2,"idOperation":14,"start":21,"end":25,"machine":10},{"id":59313,"idJob":2,"idOperation":13,"start":26,"end":28,"machine":10},{"id":59314,"idJob":2,"idOperation":15,"start":28,"end":28,"machine":10},{"id":59315,"idJob":1,"idOperation":10,"start":28,"end":29,"machine":10}]
I have n jobs and n_i operations. The operation name should be "id_job,id_operation" e.g., the operation 1 of job 1 equals "1,1".
Google chart timeline defines the color of the operation based on the name of the operation, so for all operations with the same name it will choose the same color. What I am trying to do to is to create the chart exactly (same colors for the same job) as Fig. 1, however, with the text anchor of each operation with its respective name. If I try to define the respective name for each operation I end up with the graph shown in Fig. 2.
Figure 1.
Figure 2.
My javascript code.
function timelineChart() {
$.ajax({
url : "operations",
dataType : "json",
success : function(result) {
google.charts.load('current', {
'packages' : [ 'timeline' ]
});
google.charts.setOnLoadCallback(function() {
drawChart2(result);
});
}
});
function drawChart2(result) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Machine');
data.addColumn('string', 'Job');
data.addColumn('date', 'Start Date');
data.addColumn('date', 'End Date');
var dataArray = [];
$.each(result, function(i, obj) {
dataArray.push([ 'M' + obj.machine, getIdJob(obj) + "," + getIdOp(obj), new Date(obj.start * 1000), new Date(obj.end * 1000) ])
});
data.addRows(dataArray);
var options = {
timeline : {
groupByRowLabel : true,
showRowLabels : true,
showBarLabels : true
}
};
var chart = new google.visualization.Timeline(document.getElementById('chart_timeline'));
chart.draw(data, options);
}
}
function getIdJob(obj) {
if (obj.idJob == 0) {
return 'Unavailability';
} else {
return obj.idJob;
}
}
function getIdOp(obj) {
return obj.idOperation;
}
The code bellow may work for your case. You can define a map of colors and then use it to draw your operations. You have to use DataView and remove the category before drawing.
function drawChart2(result) {
var container = document.getElementById('chart_timeline');
var chart = new google.visualization.Timeline(container);
var dataTable = new google.visualization.DataTable();
dataTable.addColumn({type : 'string',id : 'Machine'});
dataTable.addColumn({type : 'string',id : 'Category'});
dataTable.addColumn({type : 'string',id : 'ID'});
dataTable.addColumn({type : 'date', id : 'Start'});
dataTable.addColumn({type : 'date', id : 'End'});
var colorMap = {};
var dataArray = [];
$.each(result, function(i, obj) {
colorMap['Category' + getIdJob(obj)] = randomColor();
dataArray.push(
[ 'M' + obj.machine, 'Category'+getIdJob(obj), getIdJob(obj) + "," + getIdOp(obj), new Date(obj.start * 1000), new Date(obj.end * 1000) ])
});
dataTable.addRows(dataArray);
var colors = [];
for (var i = 0; i < dataTable.getNumberOfRows(); i++) {
colors.push(colorMap[dataTable.getValue(i, 1).toString()]);
}
var options = {
timeline : {
groupByRowLabel : true,
showRowLabels : true,
showBarLabels : true
},
colors : colors
};
console.log(dataTable);
// use a DataView to hide the category column from the Timeline
var view = new google.visualization.DataView(dataTable);
view.setColumns([ 0, 2, 3, 4 ]);
chart.draw(view, options);
}
We can define an extra column 'Category' and define a map with a color for each category. You can use the colors at the options and to avoid the error of extra column you can use DataView to hide the category column.
The Thymeleaf block I have made in JavaScript cuts off the ending ; of the variable, and throws an Uncaught (in promise) SyntaxError: Unexpected token ' in JSON at position 2.
The code does parse like it should, except for the data variable. Parsed code:
function drawChart() {
var jsonData = "{ 'cols': [" +
"{'id':'','label':'Expense','pattern':'','type':'string'}" +
"{'id':'','label':'Amount','pattern':'','type':'number'}]," +
"'rows': [";
var data = {'Expense1': 25.0, 'Expense2': 20.0, 'Expense3': 40.0};
var end = "]}";
var res = jsonData.concat(data);
var res = res.concat(end);
var json = JSON.parse(res);
var data = new google.visualization.DataTable(json);
var options = {
title: 'Data test',
pieHole: 0.4
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
Pre Thymeleaf code:
<script type="text/javascript" th:inline="javascript">
google.charts.load('current', {'packages': ['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = "{ 'cols': [" +
"{'id':'','label':'Expense','pattern':'','type':'string'}" +
"{'id':'','label':'Amount','pattern':'','type':'number'}]," +
"'rows': [";
var data = /*[[${chart.DataPoints}]]*/;
var end = "]}";
var res = jsonData.concat(data);
var res = res.concat(end);
var json = JSON.parse(res);
var data = new google.visualization.DataTable(json);
var options = {
title: /*[[${chart.title}]]*/'',
pieHole: 0.4
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
</script>
The data var is either like it is right now, or when enclosed in "", it cuts off the closing semi-colon. How do I get Thymeleaf of JavaScript to cast the data var to a string (while maintaining the '' it contains)?
Does this work for you? I don't think you need to build your data as a JSON string first, simply create it as a JavaScript object:
<script type="text/javascript" th:inline="javascript">
google.charts.load('current', {'packages': ['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var json = {
'cols': [
{'id':'', 'label': 'Expense', 'pattern': '', 'type': 'string'},
{'id':'', 'label': 'Amount', 'pattern': '', 'type': 'number'}
],
rows: []
};
var data = /*[[${chart.DataPoints}]]*/ [];
var rows = [];
Object.keys(data).forEach(function(key) {
rows.push({
"c": [
{"v": key, "f": null},
{"v": data[key], "f": null}
]
});
});
json['rows'] = rows;
var data = new google.visualization.DataTable(json);
var title = /*[[${chart.title}]]*/ '';
var options = {
title: title,
pieHole: 0.4
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
</script>
edit: you can format the data however you want... it's pretty trivial to do in JavaScript.
I'm trying to draw two charts using the Google Charts API. I set up my HTML like this:
<div id="page_views" data-title="{{ report['page_views']['title'] }}" data-labels="{{ report['page_views']['labels'] }}" data-rows="{{ report['page_views']['rows'] }}"></div>
<div id="event_views" data-title="{{ report['event_views']['title'] }}" data-labels="{{ report['event_views']['labels'] }}" data-rows="{{ report['event_views']['rows'] }}"></div>
where the data attributes are filled during template rendering. I then use the following javascript to attempt to draw my charts:
google.load('visualization', '1.0', {packages: ['line']});
google.setOnLoadCallback(drawCharts);
function drawPageViews() {
var data = new google.visualization.DataTable();
var page_views = document.getElementById("page_views");
var labels = eval(page_views.dataset.labels);
data.addColumn('number', "Day");
for(var i = 0; i < labels.length; i++) {
data.addColumn('number', labels[i]);
}
var rows = eval(page_views.dataset.rows);
data.addRows(rows);
var options = {
chart: {
title: page_views.dataset.title
},
width: 900,
height: 500
};
var chart = new google.charts.Line(document.getElementById('page_views'));
chart.draw(data, options);
}
function drawEventViews() {
var data = new google.visualization.DataTable();
var event_views = document.getElementById("event_views");
var labels = eval(event_views.dataset.labels);
data.addColumn('number', "Day");
for(var i = 0; i < labels.length; i++) {
data.addColumn('number', labels[i]);
}
var rows = eval(event_views.dataset.rows);
data.addRows(rows);
var options = {
chart: {
title: event_views.dataset.title
},
width: 900,
height: 500
};
var chart = new google.charts.Line(document.getElementById('event_views'));
chart.draw(data, options);
}
function drawCharts() {
drawPageViews();
drawEventViews();
}
The result that I get is that one of the charts is drawn while the other contains an SVG with an empty tag and nothing else inside. Which chart gets drawn is random. Commenting out either draw function makes the other single chart draw as expected.
It seems like there must be some sort of shared global state or variable but it looks to me like everything is defined in the different draw functions. When I look up similar questions people offer solutions which look very much like what I'm doing. What am I missing?
It seems this behavior is related with draw function, in particular it occurs once multiple charts is rendered on the page.
According to the documentation:
The draw() method is asynchronous: that is, it returns immediately,
but the instance that it returns might not be immediately available.
For rendering multiple charts on the page you could consider the following approach: render the next chart once the previous one is rendered, this is where ready event comes to the rescue.
Having said that the solution would be to replace:
function drawCharts() {
drawPageViews();
drawEventViews();
}
with
function drawCharts() {
drawPageViews(function(){
drawEventViews();
});
}
where
function drawPageViews(chartReady) {
//...
var chart = new google.charts.Line(document.getElementById('page_views'));
if (typeof chartReady !== 'undefined') google.visualization.events.addOneTimeListener(chart, 'ready', chartReady);
chart.draw(data, options);
}
and
function drawEventViews(chartReady) {
//...
var chart = new google.charts.Line(document.getElementById('event_views'));
if (typeof chartReady !== 'undefined') google.visualization.events.addOneTimeListener(chart, 'ready', chartReady);
chart.draw(data, options);
}
Working example
google.load('visualization', '1.0', { packages: ['line'] });
google.setOnLoadCallback(drawCharts);
function drawPageViews(chartReady) {
var data = new google.visualization.DataTable();
var page_views = document.getElementById("page_views");
var labels = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
data.addColumn('string', 'Day');
data.addColumn('number', 'PageViews');
var rows = new Array();
for (var i = 0; i < labels.length; i++) {
rows.push([labels[i], getRandomInt(0, 100)]);
}
data.addRows(rows);
var options = {
chart: {
title: 'Page views'
},
width: 900,
height: 500
};
var chart = new google.charts.Line(document.getElementById('page_views'));
if(typeof chartReady !== 'undefined') google.visualization.events.addOneTimeListener(chart, 'ready', chartReady);
chart.draw(data, options);
}
function drawEventViews(chartReady) {
var data = new google.visualization.DataTable();
var event_views = document.getElementById("event_views");
var labels = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
data.addColumn('string', 'Day');
data.addColumn('number', 'EventViews');
var rows = new Array();
for (var i = 0; i < labels.length; i++) {
rows.push([labels[i], getRandomInt(0, 100)]);
}
data.addRows(rows);
var options = {
chart: {
title: 'Event views'
},
width: 900,
height: 500
};
var chart = new google.charts.Line(document.getElementById('event_views'));
if(typeof chartReady !== 'undefined') google.visualization.events.addOneTimeListener(chart, 'ready', chartReady);
chart.draw(data, options);
}
function drawCharts() {
drawPageViews(function(){
drawEventViews();
});
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="page_views"></div>
<div id="event_views"></div>
In Google chart- when i call the function to remove comma from variable from input , it wont work.
What i want is result from ldsalary(without comma) update in Google chart. ldsalary value is calculated and shown while onkeyup. It will be changing.
update : made a jsfiddle
onkeyup:
document.getElementById('cal').onkeyup=function(){
calculator();
drawChart();
reformat function:
function reformat(str) {
while (str.search(",") >= 0) {
str = (str + "").replace(',', '');
}
return str;
};
Calculator function, this updates ldsalary with new value:
function calculator(){
.........
var jldsalary = document.getElementById("ldsalary");
xm = a * Math.pow(1 + jasincrease / 100, b);
jldsalary.value = rounding(xm).toLocaleString();
}
Chart:
<script type="text/javascript">
var rage = 55 ;
var slry = 5000;
google.load('visualization', '1', {packages: ['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
rage =document.getElementById('rage').value *1;
var xxx = document.getElementById('ldsalary').value *1;
// if i add this google chart wont show.
slry.value =reformat(xxx); // without reformat, there will be ',' value.
var data = new google.visualization.DataTable();
data.addColumn('number', 'X');
data.addColumn('number', 'Amount');
data.addRows([
[0, 0], [rage,slry],
[100, 0]
]);
var options = {
curveType: 'function',
width: 500,
height: 200,
hAxis: {
title: 'Age'
},
vAxis: {
title: 'Amount'
}
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
Its been a day doing all kinds of solutions. Advance thanks for helping me.
as per your code, you have defined slry as a variable, and trying to use spry.value, which is not valid at all, change:
...
slry.value =reformat(xxx); //its just a variable not input element
to
...
slry = reformat(xxx);
The problem was in reformat().
function reformat(str) {
return parseInt(str.replace(',', ''));
}
Now it works: as value in input box changes , google graph too changes.