how to plot customized JSON data on c3js pie chart? - javascript

I want to plot C3js pie chart based on the following JSON (received from HQL-hibernate Java Play framework)...
JSON looks like this (This is dynamic data):
{"ug":["K","M2","M3","M4"],"wtv":[10,20,35,60]}
HTML:
<div id="chart"></div>
JS (what I actually tried):
var json ={"ug":["K","M2","M3","M4"],"wtv":[10,20,35,60]};
var ug =json.ug;
var wtv=json.wtv;
var chart = c3.generate({
data: {
json: {
ug:wtv[0],
ug1:wtv[1],
ug2:wtv[2],
ug3:wtv[3],
},
type : 'pie',
}
});
Here is a fiddle for reference.
In places of ug,ug1,ug2,ug3 I need K,M2,M3,M4(To be noted these are dynamic data)
Can anyone help me to manipulate the data to draw the pie chart as required?
I hope changing the structure of JSON at the back end is not the only solution (it is very difficult in my case though). Any other solutions are appreciated.

so long as "ug" and "wtv" have the same number of elements...
var json = {"ug":["K","M2","M3","M4"],"wtv":[10,20,35,60]};
var pieJson = {};
json.ug.forEach(function (ug, index) {
pieJson[ug] = json.wtv[index];
});
var chart = c3.generate({
data: {
// iris data from R
json: pieJson,
type : 'pie',
}
});
jsfiddle.net/4h4z00g7/

Related

not able to display data in google charts using json

I am getting the data from MySQL and want to display it in a line chart using google charts. I am using java and javascript.
this is the type of data which i am getting from MySQL:
timestamp 2017-06-12 19:22:23.0 , 2017-06-12 19:22:25.0
f1 414 413
I got this data in a resultset and converted it into JSONarray and the output is like:
'[{"f1":414,"ts":"2017-06-12 19:22:23.0"},{"f1":415,"ts":"2017-06-12 19:22:25.0"}]'
-> from a servlet i am passing this string to a jsp file.
Now the JSP file:
<script type="text/javascript">
$(document).ready(function(){
alert('hello');
});
var newstring = <%= request.getAttribute("json_string")%>
<%System.out.println(request.getAttribute("json_string"));%>
var chartData = JSON.parse(newstring);
// Load google charts
google.load('visualization', '1.1', {packages:["corechart, table"]});
google.charts.setOnLoadCallback(drawChart);
// Draw the chart and set the chart values
var dTable = new google.visualization.DataTable();
dTable.addColumn('string','timestamp');
dTable.addColumn('number','f1');
for(i=0;i<chartData.length;i++)
{
var currentObj = chartData[i];
dTable.addRow([currentObj.f1,currentObj.ts]);
}
// Display the chart inside the <div> element with id="linechart"
var options = {'title':'<%= request.getAttribute("Spring_type") + " for date :"%><%= request.getAttribute("date")%>', 'width':550, 'height':400};
var chart = new google.visualization.LineChart(document.getElementById('linechart'));
chart.draw(data, options);
</script>
The chart is not getting displayed.
Any help would be appreciated. Or if there is any other way please write it down.
You are adding all your values to dTable while your are using some variable data while creating the chart, the correct way should be
chart.draw(dTable , options);
and there is no drawChart function , you should wrap everything in the function lioke
function drawChart(){
var dTable = new google.visualization.DataTable();
dTable.addColumn('string','timestamp');
dTable.addColumn('number','f1');
for(i=0;i<chartData.length;i++)
{
var currentObj = chartData[i];
dTable.addRow([currentObj.f1,currentObj.ts]);
}
// Display the chart inside the <div> element with id="linechart"
var options = {'title':'<%= request.getAttribute("Spring_type") + " for date :"%><%= request.getAttribute("date")%>', 'width':550, 'height':400};
var chart = new google.visualization.LineChart(document.getElementById('linechart'));
chart.draw(dTable , options);
}
Also look at this example from the api docs

D3 multiline graph with Array of objects

I am trying to build a D3 Multi-line graph for which I am getting data from jsonArray of Object which is coming from my JAVA code.
Below is the JSON I am getting.
How do I pass this data in D3 for getting a multi line graph with:
x-axis as date
y-axis as noOfColumns, and,
z-axis as fileName ?
I am trying to build a graph similar to the one below (found here):
[
{"date":["2017-12-18 13:31:02.0","2017-12-13 16:00:30.0","2017-12-18 13:30:46.0"],"fileName":"Google-1","noOfColumns":[12,22,54]},
{"date":["2017-12-18 13:29:27.0"],"fileName":"Yahoo-1","noOfColumns":[44]}
]
Posting this answer myself to help others. I made some modifications in JSON structure and changed it to below. Also, I used Dimple over D3 to make it simple and got the required graph. Below is the code spinet I used
[
{"date":"2017-12-18 13:31:02.0","fileName":"Google-1","numberOfColumns":12},
{"date":"2017-12-13 16:00:30.0","fileName":"Google-1","numberOfColumns":22}
]
<script type="text/javascript" src="../../js/d3/d3.min.js"></script>
<script src="../../js/d3/dimple.v2.3.0.js"></script>
<div id="chartContainer">
<script type="text/javascript">
var data=<%=dataforGraphNew%>;
var svg = dimple.newSvg("#chartContainer", 590, 400);
var myChart = new dimple.chart(svg, data);
myChart.setBounds(60, 30, 505, 305);
var x = myChart.addCategoryAxis("x", "date");
x.addOrderRule("date");
var y = myChart.addCategoryAxis("y","numberOfColumns");
var s = myChart.addSeries("fileName", dimple.plot.line);
s.interpolation = "cardinal";
myChart.addLegend(60, 10, 500, 20, "right");
myChart.draw();
</script>
</div>

Locale language for google charts not working

In my page I load the chart as described in the docs. It's a view in asp.net that renders the output. The view checks if a class called Avstemning is populated then puts strings from that class into the chart as data. But if I use Norwegian letters like ø,æ, å. The chart data can't read it even as I specify the language option to use. What is going on here?
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
#if (Model.Avstemning != null)
{
<script type="text/javascript">
google.charts
.load('current', { 'packages': ['corechart'], 'language':'no' });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Avstemning', '#Model.Avstemning.Tittel'],
['#Model.Avstemning.Option1', #Model.Avstemning.One],
['#Model.Avstemning.Option2', #Model.Avstemning.Two],
['#Model.Avstemning.Option3', #Model.Avstemning.Three]
]);
var options = {
title: '#Model.Avstemning.Tittel'};
var chart = new
google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
}
If I change the data variable to take hard coded options with norwegian letters it works. But that's not exactly ideal. Any ideas on how to solve this? Inject javascript from controller?
I solved the encoding issue by using Html.Raw(). Not recommended if these are later to be stored in db, but works for displaying the data as I intended:
var data = google.visualization.arrayToDataTable([
['Avstemning', '#Html.Raw(Model.Avstemning.Tittel)'],
['#Html.Raw(Model.Avstemning.Option1)', #Model.Avstemning.One],
['#Html.Raw(Model.Avstemning.Option2)', #Model.Avstemning.Two],
['#Html.Raw(Model.Avstemning.Option3)', #Model.Avstemning.Three]
]);
var options = {
title: '#Html.Raw(Model.Avstemning.Tittel)',
};

create Google Chart through AJAX call with JSON/JS

CI'm having an issue creating a chart. I've read number of tutorials and basically wrote a code according to them. However, the problem is that the chart won't be displayed at all.
I want on AJAX call to retrieve data from SQLite3 and then draw a chart based on that data.
It could be Column or Pie chart, doesnt matter.
I'm pretty sure there is some kind of problem with the way I work on JSON, and I would like someone to help me. Thanks!
#test.html
-------------------------------------------------------------------------
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
function drawChart() {
var jsonData = $.ajax({
url: "test-return.php",
dataType: "json",
async: false
}).responseText;
document.getElementById('rightDiv').innerHTML = jsonData;
var jsonData2 = [["FC Internazionale ",24],["AS Roma ",24],["Milan AC ",20],["UC Sampdoria ",19],["US Citt\u00e0 di Palermo",18],["SSC Napoli ",15],["Juventus FC ",16],["Parma FC ",14],["Genoa CFC ",14],["AS Bari ",13],["AC Fiorentina ",13],["SS Lazio ",11],["Calcio Catania ",10],["Cagliari Calcio ",11],["Udinese Calcio ",11],["AC Chievo Verona ",12],["Bologna FC ",10],["Atalanta BC ",9],["AC Siena ",7],["AS Livorno Calcio ",7]];
var data = google.visualization.arrayToDataTable(jsonData2,true);
var options = {
title: 'table 1'
};
var chart = new google.visualization.ColumnChart(
document.getElementById('chart_div'));
chart.draw(data, options);
}
google.load('visualization', '1', {packages:['corechart'], callback: drawChart});
</script>
</head>
<body>
<div id="chart_div" style="width: 400px; height: 500px;"></div>
<div id="rightDiv">query results</div>
</body>
</html>
#test-return.php
-----------------------------------------------------------------------------
<?php
sqlite code here
................
echo json_encode($row_array);
?>
$row_array output => [["FC Internazionale ",24],["AS Roma ",24],["Milan AC ",20],["UC Sampdoria ",19]......
You have to match your data format to format expected by your chosen chart type. As-is, you will have 3 columns of data: one numeric, one string, and one numeric. The PieChart expects two columns of data: the first should be type "string" and the second should be type "number". ColumnCharts can have any number of columns: the first can be either type "number", "date", "datetime", "timeofday", or "string", but all of the following columns should be type "number" (usually, that is - there are some exceptions that have to do with using column roles which are outside the scope of what you are doing here).
Looking at your data, I am speculating that the first column (the 1, 2, 3, 4... in your sample data) is a row number and not something you intend to plot. If this is the case, you need to adjust your server-side code to remove it. If this is not the case, can you provide information about it so I can help you figure out how to use it?
Also, your data is missing column headers. As structured, the arrayToDataTable method will take the first row of data and use it as the column headers, so you would get three columns with the labels "1", "FC Internazionale ", and "24", which you probably don't want. Either amend your server-side code to make the first row of data contain column labels, or set the second argument in the arrayToDataTable call to true.
By using jsonData = $.ajax(...).responseText;, you are bypassing the JSON conversion that jQuery does and passing the raw text of the response to jsonData. Since you need a javascript array to use the arrayToDataTable method, you need to call JSON.parse on jsonData to convert it to an array:
var data = google.visualization.arrayToDataTable(JSON.parse(jsonData), true);

Exporting ng-grid data to CSV and PDF format in angularjs

Please Help me....any plugin is there..?
I have searched for exporing excel and PDF in angularjs. using ng-grid.
Exporting ng-grid data to CSV and PDF format in angularjs
For csv export there is the ngGridCsvExportPlugin that you can find here
Just at a reference to the script and add the ngGridCsvExportPlugin to the gridOptions (and activate the footer too by adding showFooter : true to the gridOption)
$scope.gridOptions = {
data: 'myData',
plugins: [new ngGridCsvExportPlugin()],
showFooter: true,
};
A basic plunker where you can see it at work can be found here
You don't need any external plugin now. ng grid which new version is called now UI-Grid has native support. Method names are csvExport and pdfExport.
http://ui-grid.info/docs/#/tutorial/206_exporting_data
If you are able to do something outside of angular you could use https://github.com/Ziv-Barber/officegen for excel. See here https://stackoverflow.com/questions/18476921/angularjs-generating-a-pdf-client-side for pdfs.
I used jsPDF. It's the simplest ever.
Include it in your html:
<script src="jspdf.min.js"></script>
<!-- script src="jspdf.debug.js"></script--><!-- for development -->
Use it1:
var doc = new jsPDF();
doc.text(20, 20, 'Hello world.');
doc.save('Test.pdf');
And bind your button or whatever to this code.
Advanced Tip
I also found the jsPDF-AutoTable plugin-for-jsPDF extremely useful.
Include it in your html:
<script src="jspdf.plugin.autotable.js"></script>
In the controller, transfer data from ng-grid data to jsPDF, using jsPDF-AutoTable plugin.
Assuming you define your ng-grid table:
$scope.gridOptions = {
data: 'myData',
columnDefs: [
{field: 'user', displayName: 'User' /*,...*/ },
{field: 'email', displayName: 'Email' /*,...*/ },
{field: 'favoriteShruberry', displayName: 'Favorite Shrubbery' /*,...*/ }
]
};
... Then, in the function that generates the pdf:
var columns = [];
var rows = [];
// copy ng-grid's titles to pdf's table definition:
var allColumnDefs = $scope.gridOptions.columnDefs;
for ( var columnIdx in allColumnDefs ) {
var columnDef = allColumnDefs[columnIdx];
var newColumnDef = {
title: columnDef.displayName,
dataKey: columnDef.field
};
columns.push(newColumnDef);
}
// copy ng-grid's actual data to pdf's table:
var allRecords = $scope.myData;
for ( var recordIdx in allRecords ) {
var record = allRecords[recordIdx];
var newRow = {};
for ( var columnIdx in allColumnDefs ) {
var columnDef = allColumnDefs[columnIdx];
var value = record[columnDef.field];
if (value !== null) {
newRow[columnDef.field] = value;
}
}
rows.push(newRow);
}
var docName = 'favoriteShrubberies.pdf';
var pdfStyle = { styles: { overflow: 'linebreak' } } // this handles cells that contain really long text like in this comment, by auto-inserting a
// line break inside the cell, causing the whole line's height to increase accordingly
var doc = new jsPDF('p', 'pt'); // currently supports only 'pt'
doc.autoTable(columns, rows, pdfStyle);
doc.save(docName);
1 Example is straight from the jsPDF GitHub repo
Very late to this party, but I wrote a PDF output that works for me. There is a plunker, and it is available as a plugin for V2 of ng-grid, but it doesn't look like they have taken it through into V3 (but I just had a very quick peek, so I could be wrong).

Categories

Resources