javascript - How to draw a line graph using d3.js? -
i new d3.js , trying graph 3 lines on same plot. i'm reading tsv file 4 columns: time, x, y, , z. accelerometer data. want plot x,y,z columns vs time can't seem it. suggestions?
function graph(){ // set dimensions of canvas / graph var margin = {top: 30, right: 20, bottom: 30, left: 50}, width = 600 - margin.left - margin.right, height = 270 - margin.top - margin.bottom; // set ranges var x = d3.time.scale().range([0, width]); var y = d3.scale.linear().range([height, 0]); // define axes var xaxis = d3.svg.axis().scale(x) .orient("bottom").ticks(5); var yaxis = d3.svg.axis().scale(y) .orient("left").ticks(5); // define line var valueline = d3.svg.line() .x(function(d) { return x(d.time); }) .y(function(d) { return y(d.x); }); var valueline2 = d3.svg.line() .x(function(d) { return x(d.time); }) .y(function(d) { return y(d.y); }) var valueline3 = d3.svg.line() .x(function(d) { return x(d.time); }) .y(function(d) { return y(d.z); }); // adds svg canvas var svg = d3.select("body") .append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); // data d3.tsv("data/data2.tsv", function(error, data) { data.foreach(function(d) { d.time = +d.time; d.x = +d.x; d.y = +d.y; d.z = +d.z; }); // scale range of data x.domain(d3.extent(data, function(d) { return d.time; })); y.domain([0, d3.max(data, function(d) { return math.max(d.x, d.y, d.z); })]); // add valueline path. svg.append("path") // add valueline path. .attr("class", "line") .attr("d", valueline(data)); svg.append("path") // add valueline path. .attr("class", "line") .style("stroke", "red") .attr("d", valueline2(data)); svg.append("path") // add valueline path. .attr("class", "line") .style("stroke", "green") .attr("d", valueline3(data)); // add x axis svg.append("g") // add x axis .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xaxis); // add y axis svg.append("g") // add y axis .attr("class", "y axis") .call(yaxis); });}
you can add each line 1 @ time canvas it's not d3 or efficient. it's better organise data in appropriate way. the main issue way data's been prepared. in example lar's pointed data nested using block of code:
var series = color.domain().map(function(name) { return { name: name, values: data.map(function(d) { return { time: d.time, score: +d[name] }; }) }; });
and create array of 3 objects. each object has key value pair: name , array. in each array object contains time , score information plotting. last array of object passed line generator.
i've created fiddle, here, that's heavily based on example lar's has pointed , it's commented throughout. trick @ stage inspect elements , use console.log
best of luck.
Comments
Post a Comment