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>
Related
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
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/
I am trying to use c3.js timeseries line chart (URL : http://c3js.org/samples/timeseries.html). The only difference being that I am using the CDN link to the js files instead of downloading them. However I keep getting the following error
Chrome
Uncaught Error: x is not defined for id = "date".
Firefox
Error: x is not defined for id = "date".
throw new Error('x is not defined for id = "' + id + '".');
|
------------+
The html file is given below
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<head>
<link rel="stylesheet" type="text/css" href="http://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.css"/>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.js"></script>
<script>
var dates = ['20130101', '20130102', '20130103', '20130104', '20130105', '20130106'];
var sample = [30, 200, 100, 400, 150, 250];
var chart = c3.generate({
bindto: '#chart',
data: {
x:'Dates',
x_format:'%Y%m%d',
columns: [
//['Dates'].concat(dates),
//['Sample'].concat(sample)
['date', '20130101', '20130102', '20130103', '20130104', '20130105', '20130106'],
['sample', 30, 200, 100, 400, 150, 250]
]
},
axis: {
x: {
type : 'timeseries'
}
}
});
</script>
</head>
<body>
<div id="chart"></div>
</body>
</html>
I am not sure why I am getting the date related errors. I tried using actual data values in the C3 arguments as well as passing the data as variables. Any help is highly appreciated
Your dates array needs a first value with the name/id of the 'set', such as:
var dates = ['Dates', '20130101', '20130102', '20130103', '20130104', '20130105', '20130106'];
The data object's x property needs to match this. In the code above you've got differing values: Dates and date.
data: { x:'Dates',
You were closer with the concat attempt.
See this link: http://jsfiddle.net/jrdsxvys/16/
I start to use Dygraphs recently,
and I found that if data have only one record,
there is no label show on the x-axis under the graph.
For Example, using the code from tutorial of Dygraphs site :
<html>
<head>
<script type="text/javascript"
src="dygraph-combined-dev.js"></script>
</head>
<body>
<div id="graphdiv"></div>
<script type="text/javascript">
g = new Dygraph(
// containing div
document.getElementById("graphdiv"),
// CSV or path to a CSV file.
"Date,Temperature\n" +
"2008-05-07,75\n" +
"2008-05-08,70\n" +
"2008-05-09,80\n"
);
</script>
</body>
</html>
I change the data to one record:
// CSV or path to a CSV file.
"Date,Temperature\n" +
"2008-05-07,75\n"
No label is shown on x-axis.
I have tried to have a look on the options reference of Dygraphs,
but seems no option is for drawing the label when data have only one record.
Any idea how to draw the label when only one record is being inputted?
With just one value, dygraphs has no sense for the scale of your data. Should the x-axis span a year? A month? A century?
The solution is to set the scale explicitly:
g = new Dygraph(
// containing div
"graphdiv",
// CSV or path to a CSV file.
"Date,Temperature\n" +
"2008-05-07,75\n",
{
dateWindow: [new Date(2008, 0, 0), new Date(2008, 11, 30)]
}
);
Here is my code which is right as per my knowledge. Because I created similar PIE chart successfully,
Error is : Unknown Header Type : 24
I think error is in parsing data from csv file. But it parsed correctly in string & int form.
Can someone tell what is the issue here.
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script src="http://jquery-csv.googlecode.com/files/jquery.csv-0.71.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["gauge"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
// grab the CSV
$.get("Chart2-data.csv", function(csvString) {
// transform the CSV string into a 2-dimensional array
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
//alert(arrayData);
// this new DataTable object holds all the data
var data = new google.visualization.arrayToDataTable(arrayData);
// this view can select a subset of the data at a time
var view = new google.visualization.DataView(data);
view.setColumns([0,1]);
// set chart options
var options = {
title: "A Chart from a CSV!",
hAxis: {title: data.getColumnLabel(0), minValue: data.getColumnRange(0).min, maxValue: data.getColumnRange(0).max},
vAxis: {title: data.getColumnLabel(1), minValue: data.getColumnRange(1).min, maxValue: data.getColumnRange(1).max},
legend: 'none'
};
var chart = new google.visualization.Gauge(document.getElementById('gauge'));
chart.draw(data, options);
});
}
</script>
</head>
<body>
<div id="gauge" style="width: 900px; height: 500px;"></div>
</body>
</html
>
csv data:
Engine,24
min,34
max,0
yellowFrom,10
yellowTo,6
redFrom,6
redTo,0
I was having the same problem.
Using Firebug on my DB result I was able to identify that the problem was that the google library threating a numeric value as an array header.
My array is the following
[['234 234 - ',234.00],['234 234 - ',234.00],['cuarta zzzzzzzzz prueba htmlzzzzzzz - ',654999.00],['fulanita de tal - ',150.00],['fulanita de tal - ',133.00],['Mario Alvarez Alvarez - tony',125143.20],['otra5555 prueba5555 - ',1866.00],['prieba de insert actualizando - ',1101.00],['prueba 888 - ',987.00],['prueba con html - ',854.00],['prueba de guardado - ',123.00],['prueba de insert - ',369.00],['prueba insert actualizando 02 - ',753.00],['prueba666 7777 - ',1547.00],['prueba666 7777 - ',1547.00],['prueba88888 de guardado8888 - ',1576.00],['tercera prueba - ',98765.00]]
My javascript error was:
Error: Unknown header type: 234
The solution is explained in the Google Visualization API Reference:
google.visualization.arrayToDataTable(twoDArray, opt_firstRowIsData)
Check this link for detailed info
You have to explicit tell the library that the first row is data, not a header. I add the second parameter true like this:
var data = google.visualization.arrayToDataTable(vArray, true);
PD: My web app was working fine until a few days ago. I guess google did some change to the library.
Hope my explain will help you