Pass columns numbers using Javascript for google charts plots - javascript

I have CSV data in the following format:
Customer , Key1 , Key2 , Key 3 , Key4 , Sum , Total
GOOGLE, 101 ,6 , 3, 2, 6, 100 ,121
AAPLE , 12 ,12,34,21,4,66,112
I just need columns Customer , Key1 , Key2 , Key 3 , Key4 need to exclude Sum , Total
Can someone help me in google charts how do i do that?
<body>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script>
<script type="text/javascript">
google.charts.load('current', {
callback: function () {
$.get("failures.csv", function(csvString) {
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
console.log(arrayData);
var data = new google.visualization.arrayToDataTable(arrayData);
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data);
});
},
packages: ['corechart']
});
</script>
<div id="chart_div"></div>
</body>

create a data view, use hide columns method, then draw chart with data view...
var data = google.visualization.arrayToDataTable(arrayData); // <-- new keyword not needed here
var view = new google.visualization.DataView(data);
view.hideColumns([5, 6]);
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(view);
or you can use the set columns method, to specify which columns to use...
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, 2, 3, 4]);

Related

How to convert JSON object to JavaScript array with two key to use in google chart?

I need to put a json from eloquent in a google chart but I can't convert the result from eloquent to a correct dataTable
//activos represents result from eloquent
var activos = [
{"descripcion":"peri\u00f3dico","riesgo":"5"},
{"descripcion":"autom\u00e1ticas ","riesgo":"2"},
{"descripcion":" \tAusencia","riesgo":"2"},
{"descripcion":" \tAusencia de alto riesgo","riesgo":"4"},
{"descripcion":"negocio","riesgo":"3"}
];
google.charts.load('current', {
'packages': ['corechart']
});
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Descripcion');
data.addColumn('number', 'Cantidad');
data.addRows(activos);
// Set chart options
var options = {
'title': 'Reporte de Activos',
'width': 400,
'height': 300,
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
the chart doen't apear
Instead of:
data.addRows(activos);
Use something like this:
for(let j in activos){
data.addRows([activos[j].descripcion, activos[j].riesgo]);
}
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
<script src='//www.gstatic.com/charts/loader.js'></script>
<script>
var activos = [
{"descripcion":"peri\u00f3dico","riesgo":"5"},
{"descripcion":"autom\u00e1ticas ","riesgo":"2"},
{"descripcion":" \tAusencia","riesgo":"2"},
{"descripcion":" \tAusencia de alto riesgo","riesgo":"4"},
{"descripcion":"negocio","riesgo":"3"}
];
const loadchart=function(){
let dataTbl = new google.visualization.DataTable();
dataTbl.addColumn( 'string', 'Descripcion' );
dataTbl.addColumn( 'number', 'Cantidad' );
activos.forEach( obj=>{
let data=[ obj['descripcion'], parseInt( obj['riesgo'] ) ];
dataTbl.addRows( [ data ] );
});
let chart = new google.visualization.PieChart( document.getElementById('chart') );
chart.draw( dataTbl,{ width:400, height:300, title:'Reporte de Activos' } );
}
google.charts.load( 'current', {'packages':['corechart'] } );
google.charts.setOnLoadCallback( loadchart );
</script>
</head>
<body>
<div id='chart'></div>
</body>
</html>

Creating Table in Google App Script With Date Column

I am currently querying a table from Google sheet which has a Date column. The date column in my dashboard has time info included, which I want to remove; also the starting date in my code is 12/18/2018 but my dashboard starts with one day earlier. 12/17/2018 16.00
My Data source looks like this:
My Dashboard looks like this:
My Code Looks like this.
Code.gs:
function doGet(e) {
return HtmlService
.createTemplateFromFile("Line Chart multiple Table")
.evaluate()
.setTitle("Google Spreadsheet Chart")
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function getSpreadsheetData() {
var ssID = "1jxWPxxmLHP-eUcVyKAdf5pSMW6_KtBtxZO7s15eAUag";
var sheet = SpreadsheetApp.openById(ssID).getSheets()[1];
var data1 = sheet.getRange('A2:F9').getValues();
var data2 = sheet.getRange('A2:F9').getValues();
var rows = {data1: data1, data2: data2};
var r = JSON.stringify(rows);
return r;
}
Line Chart multiple Table.html
<!DOCTYPE html>
<html>
<head>
<script src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
<div id="linechartweekly"></div>
<div id="table2"></div>
<div class = "block" id="message" style="color:red;">
<script>
google.charts.load('current', {'packages':['table']});
google.charts.load('current', {packages: ['corechart', 'line']});
google.charts.setOnLoadCallback(getSpreadsheetData);
function display_msg(msg) {
console.log("display_msg():"+msg);
document.getElementById("message").style.display = "block"; // Style of display
var div = document.getElementById('message');
div.innerHTML = msg;
}
function getSpreadsheetData() {
google.script.run.withSuccessHandler(drawChart).getSpreadsheetData();
}
function drawChart(r) {
// Parse back to an object
var rows = JSON.parse(r);
console.log("rows:"+rows);
var data1 = google.visualization.arrayToDataTable(rows.data1, false);
var data2 = google.visualization.arrayToDataTable(rows.data2, false);
var options1 = {
title: 'SPC Chart weekly',
legend: ['USL', 'UCL', 'Data', 'LCL', 'LSL'],
colors: ['Red', 'Orange', 'blue', 'Orange', 'Red'],
pointSize: 4,
};
var chart1 = new google.visualization.LineChart(document.getElementById("linechartweekly"));
chart1.draw(data1, options1);
var table2 = new google.visualization.Table(document.getElementById("table2"));
table2.draw(data2, {showRowNumber: false, width: '50%', height: '100%'});
}
function failure_callback(error) {
display_msg("ERROR: " + error.message);
console.log('failure_callback() entered. WTF'+error.message);
}
</script>
</body>
</html>
May I know how to change my date to the right format removing the time and also ensure the correct starting date
Any help is much appreciated.
The actual problem has me stumped, but I do have a workaround; see modified code example below, with some additional error handling.
I've extensively tested the server-side function, and from its perspective there is absolutely no difference in the row object that is created whether the range starts at column 'I' or 'J'.
The problem manifests itself in the client-side success handler which, when column 'I' is included is essentially passed a null argument, note the whole object, not just the row.data1 part, is null.
The row object that is being passed from the server to the client is quite complicated (an object with 3 key value pairs, where the values are fairly long arrays). I can't see anything in the GAS documentation that disallows this: Legal parameters and return values are JavaScript primitives like a Number, Boolean, String, or null, as well as JavaScript objects and arrays that are composed of primitives, objects and arrays. So this could be a bug?
The workaround, illustrated in the code examples below is to stringify the object in the server-side function, and then parsing it back to an object in the client.
HTML
<!DOCTYPE html>
<html>
<head>
<script src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
<div id="table1"></div>
<div id="linechartweekly"></div>
<div id="table2"></div>
<div class = "block" id="message" style="color:red;">
<script>
google.charts.load('current', {'packages':['table']});
google.charts.load('current', {packages: ['corechart', 'line']});
google.charts.setOnLoadCallback(getSpreadsheetData);
function display_msg(msg) {
console.log("display_msg():"+msg);
document.getElementById("message").style.display = "block"; // Style of display
var div = document.getElementById('message');
div.innerHTML = msg;
}
function getSpreadsheetData() {
google.script.run.withFailureHandler(failure_callback).withSuccessHandler(drawChart).getSpreadsheetData();
}
function drawChart(r) {
// Parse back to an object
var rows = JSON.parse(r);
console.log("rows:"+rows);
var data1 = google.visualization.arrayToDataTable(rows.data1, false);
var data2 = google.visualization.arrayToDataTable(rows.data2, false);
var data3 = google.visualization.arrayToDataTable(rows.data3, false);
var options1 = {
title: 'SPC Chart weekly',
legend: ['USL', 'UCL', 'Data', 'LCL', 'LSL'],
colors: ['Red', 'Orange', 'blue', 'Orange', 'Red'],
pointSize: 4,
};
var table1 = new google.visualization.Table(document.getElementById("table1"));
table1.draw(data1, {showRowNumber: false, width: '50%', height: '100%'});
var chart1 = new google.visualization.LineChart(document.getElementById("linechartweekly"));
chart1.draw(data2, options1);
var table2 = new google.visualization.Table(document.getElementById("table2"));
table2.draw(data3, {showRowNumber: false, width: '50%', height: '100%'});
}
function failure_callback(error) {
display_msg("ERROR: " + error.message);
console.log('failure_callback() entered. WTF'+error.message);
}
</script>
</body>
</html>
Code
function doGet(e) {
return HtmlService
.createTemplateFromFile("Line Chart multiple Table")
.evaluate()
.setTitle("Google Spreadsheet Chart")
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function getSpreadsheetData() {
var ssID = "1jxWPxxmLHP-eUcVyKAdf5pSMW6_KtBtxZO7s15eAUag";
var sheet = SpreadsheetApp.openById(ssID).getSheets()[0];
//var firstrow = 6; //11th row
//var range = sheet.getRange(firstrow, 1, sheet.getLastRow() - firstrow + 1, 6);
//var data1 = range.getValues();
var d1 = sheet.getRange('A1:B5').getValues();
var d2 = sheet.getRange('I2:O4').getValues();
var d3 = sheet.getRange('I2:O4').getValues();
var rows = {data1: d1, data2: d2, data3: d3};
// Stringify the object
var r = JSON.stringify(rows);
return r;
}

How can I add my Map<String, Integer > from my #Controller to the google api pie chart using thymeleaf

I have a problem I don't know how to add my Map with datas from my db to the google.visualization.arrayToDataTable in the Thymeleaf template.
I succeeded to show the map in the view with the console log but my problem is how to add it to the google.visualization.arrayToDataTable.
This is my code from #Controller
#GetMapping("/pourcentageAges")
public String ageDesClients(Model model){
Map<String,Integer>listeAgesTranches =
utilisateurMetier.agesClientsClub();
System.out.println("je suis la tailme de la liste
"+listeAgesTranches.size());
model.addAttribute("liste",listeAgesTranches);
model.addAttribute("tailleListe",listeAgesTranches.size());
return "utilisateur/agePourcentage";
}
And this is my code from my view:
So I repeat I need just to assign the " var ageList" to the google.visualization.arrayToDataTable
<script type="text/javascript" th:inline="javascript" >
// Load google charts
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
/*<![CDATA[*/
var ageList=new Map();
var tailleListe= /*[[${tailleListe}]]*/
ageList= /*[[${liste}]]*/ 'default';
/*]]>*/
// Draw the chart and set the chart values
// for (i=0; i<tailleListe;i++){
// console.log('je suis la'+[Object.keys(message)[i],Object.values(message)[i]])
// }
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'ages between 16 and 90 group by 10'],
['age betweeen 20-30',5 ]
]);
// Optional; add a title and set the width and height of the chart
var options = {'title':'Ages en pourcent de 16 a 90 ans', 'width':550,
'height':400,is3D: true};
// Display the chart inside the <div> element with id="piechart"
var chart = new
google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
Thank you a lot for any advice.
first, create a new array before using arrayToDataTable
then you can use the concat method to combine the column headings with ageList
then pass the new array to arrayToDataTable
try it like this...
<script type="text/javascript" th:inline="javascript" >
// Load google charts
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
/*<![CDATA[*/
var ageList=new Map();
var tailleListe= /*[[${tailleListe}]]*/
ageList= /*[[${liste}]]*/ 'default';
/*]]>*/
function drawChart() {
var dataArray = [
['Task', 'ages between 16 and 90 group by 10']
];
dataArray = dataArray.concat(ageList);
var data = google.visualization.arrayToDataTable(dataArray);
// Optional; add a title and set the width and height of the chart
var options = {'title':'Ages en pourcent de 16 a 90 ans', 'width':550, 'height':400,is3D: true};
// Display the chart inside the <div> element with id="piechart"
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>

pie chart does not view although I use Table is working

I am trying to view Pie chart with JSON format data when I am trying to use Table chart is working fine
I think the problem is parsing the JSON but I do not know where it is exactly
I also checked questions on this topic but not using it just like that they are using PHP as server-side but not like that on the HTML Page with javascript
That is the code
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {
callback: drawChart,
packages:['table']
});
function drawChart() {
var jsonData = [
{"Car":23,"Bus":2,"Motorcycle":10,"Person":7},
{"Car":5,"Bus":6,"Motorcycle":9,"Person":8},
{"Car":10,"Bus":20,"Motorcycle":36,"Person":13}
];
var gglData = [];
if (jsonData.length > 0) {
// load column headings
var colHead = [];
Object.keys(jsonData[0]).forEach(function (key) {
colHead.push(key);
});
gglData.push(colHead);
// load data rows
jsonData.forEach(function (row) {
var gglRow = [];
Object.keys(row).forEach(function (key) {
gglRow.push(row[key]);
});
gglData.push(gglRow);
});
}
var data = google.visualization.arrayToDataTable(gglData);
var table = new google.visualization.Table(document.getElementById('table_div'));
table.draw(data);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="table_div"></div>
</body>
</html>
first, you have to include package --> 'corechart'
next, check the data format for a pie chart,
the data needs to be in rows vs columns...
see following working snippet,
each key / value pair is added as a separate row,
then the group() method is used to aggregate...
google.charts.load('current', {
callback: drawChart,
packages:['corechart', 'table']
});
function drawChart() {
var jsonData = [
{"Car":23,"Bus":2,"Motorcycle":10,"Person":7},
{"Car":5,"Bus":6,"Motorcycle":9,"Person":8},
{"Car":10,"Bus":20,"Motorcycle":36,"Person":13}
];
var gglData = [['Vehicle', 'Value']];
jsonData.forEach(function (row) {
Object.keys(row).forEach(function (key) {
gglData.push([key, row[key]]);
});
});
var data = google.visualization.arrayToDataTable(gglData);
var groupData = google.visualization.data.group(
data,
[0],
[{column: 1, aggregation: google.visualization.data.sum, type: 'number'}]
);
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(groupData);
var table = new google.visualization.Table(document.getElementById('table_div'));
table.draw(groupData);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
<div id="table_div"></div>

Google chart prints "Table has no columns" in all cases?

I'm trying to generate a line graph with the help of google chart. But, I see "table has no columns". I tried example given on google site and observed the same. Following is my code:
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var jsonDataString = "{\"cols:\":{\"Time\":\"\",\"Sensor-1\":\"\",\"Sensor-2\":\"\",\"Sensor-3\":\"\",\"Sensor-4\":\"\"},\"rows\":[{\"1\":[{\"Sensor-1\":1024,\"Sensor-2\":1024,\"Sensor-3\":1024,\"Sensor-4\":1024}]},{\"2\":[{\"Sensor-1\":1024,\"Sensor-2\":1024,\"Sensor-3\":1024,\"Sensor-4\":1024}]},{\"3\":[{\"Sensor-1\":1024,\"Sensor-2\":1024,\"Sensor-3\":1024,\"Sensor-4\":1024}]},{\"4\":[{\"Sensor-1\":1024,\"Sensor-2\":1024,\"Sensor-3\":1024,\"Sensor-4\":1024}]},{\"5\":[{\"Sensor-1\":1024,\"Sensor-2\":1024,\"Sensor-3\":1024,\"Sensor-4\":1024}]},{\"6\":[{\"Sensor-1\":1024,\"Sensor-2\":1024,\"Sensor-3\":1024,\"Sensor-4\":1024}]},{\"7\":[{\"Sensor-1\":1024,\"Sensor-2\":1024,\"Sensor-3\":1024,\"Sensor-4\":1024}]},{\"8\":[{\"Sensor-1\":1024,\"Sensor-2\":1024,\"Sensor-3\":1024,\"Sensor-4\":1024}]},{\"9\":[{\"Sensor-1\":1024,\"Sensor-2\":1024,\"Sensor-3\":1024,\"Sensor-4\":1024}]},{\"10\":[{\"Sensor-1\":1024,\"Sensor-2\":1024,\"Sensor-3\":1024,\"Sensor-4\":1024}]}]}";
var jsonData = JSON.parse(jsonDataString);
console.log(jsonData);
var data = new google.visualization.DataTable(jsonData);
var options = {
title: 'time - temp',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="curve_chart" style="width: 900px; height: 500px"></div>
</body>
</html>
Any idea, where am I going wrong?
Thanks.
Your JSON object isn't formatted properly to generate a datatable directly from it. The accepted JSON format is :
{
"cols": [
{"label":"Topping","type":"string"},
{"label":"Slices","type":"number"}
],
"rows": [
{"c":[{"v":"Mushrooms"},{"v":3}]},
{"c":[{"v":"Onions"},{"v":1}]},
{"c":[{"v":"Olives"},{"v":1}]},
{"c":[{"v":"Zucchini"},{"v":1}]},
{"c":[{"v":"Pepperoni"},{"v":2]}
]
}
A nested JSON object with a 'cols' array containing X number of objects, where X = your number of columns, and a 'rows' array, containing Y number of 'c' nodes, where Y = your number of rows, and inside each 'c' node, Z number 'v' nodes, where Z = your number of columns.
You should check google documentation here :
Google JSON DATA
P.S Try replace your JSON string by the one provided in my example and you'll see that your line chart will be drawn as I don't see any errors in your code.

Categories