javascript - Creating a categorical bar chart from csv file in c3.js -
i have code simple bar chart using c3.js:
<!doctype html> <html lang="en"> <head> <title>c3</title> <meta charset="utf-8" /> <link href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.js"></script> </head> <body> <div id="chart"></div> <script> var chart = c3.generate({ data: { url: 'data/output.csv' type: 'bar' } }); </script> </body> </html>
the file output.csv
looks this:
a,b,c,d 25,50,75,100
and graph ends looking this:
which of data in 1 group.
what i'd want producing following, without hard coding data, rather, getting csv file first example:
<!doctype html> <html lang="en"> <head> <title>c3</title> <meta charset="utf-8" /> <link href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.js"></script> </head> <body> <div id="chart"></div> <script> var chart = c3.generate({ bar: { width: 15 }, padding: { left: 60 }, data: { x: 'letter', columns: [ ['letter', 'a','b','c','d'], ['value', 25,50,75,100] ], type: 'bar', onclick: function(e) { console.log(ylist[e.x]);a = this;} }, axis: { x: { type: 'category' } }, legend: { show: false } }); </script> </body> </html>
which give graph looks this:
here jfiddle link.
my main issue not knowing if there way split csv file categories, since seems c3.js put csv file time series.
c3 uses first line in csv header line , returns set of objects {a:25},{b:50} c3 find difficult/impossible use in way you'd like.
instead parse csv outside chart using d3's parserows function. prepend row descriptor c3 can use know bit of file what.
https://jsfiddle.net/bm57gye5/2/
// separate bit of html explained below <pre id="data"> a,b,c,d 25,50,75,100 </pre> // actual javascript var unparseddata = d3.select("pre#data").text(); var data = d3.csv.parserows( unparseddata ); data[0].splice (0,0,"letter"); data[1].splice (0,0,"data"); console.log ("data", data); var chart = c3.generate({ bar: { width: 15 }, padding: { left: 60 }, data: { columns: data, x: "letter", type: 'bar', onclick: function(e) { console.log(ylist[e.x]);a = this;} }, axis: { x: { type: 'category' } }, legend: { show: false } });
to access csv url (in jsfiddle reference data part of html) feed csv.parserows you'll need use d3.text , callback so:
d3.text("data/output.csv", function(unparseddata) { var data = d3.csv.parserows(unparseddata); ... parsing / c3 chart generation continues on here above ... }
Comments
Post a Comment