javascript - Create a line with D3 -


i'm new d3, , want use xy coordinates in linedata create series of lines connected each other. when run code, don't errors nothing shows either. doing wrong?

also, know work if use json, i'm trying apply d3 has array of data below, want avoid that.

// x, y, x, y, ... etc. var linedata = [1, 5, 20, 20, 40, 10, 60, 40, 80, 5, 100, 60];  var svgcontainer = d3.select("body").append("svg")     .attr("width", 200)     .attr("height", 200);  var x = 0;  while (x < 11) {     var linefunction = d3.svg.line()         .x(linedata[x])         .y(linedata[x + 1])         .interpolate("linear");      var linegraph = svgcontainer.append("path")         .attr("d", linefunction(linedata))         .attr("stroke", "blue")         .attr("stroke-width", 2)         .attr("fill", "none");      x++; } 

assuming want plot values in linedata on y-axis, standard step (eg 10) on x-axis, can this:

var linefunction = d3.svg.line()     .x(function(d, i) { return (i * 10); })     .y(function(d) { return d; })     .interpolate("linear");  svgcontainer.append("svg:path").attr("d", linefunction(linedata)); 

fiddle: http://jsfiddle.net/henbox/4e2rkm5d/

the key thing know through linefunction(linedata), calling linefunctionfor each point in data array: no need loop through manually d3

update

alternatively if want linedata interpreted [x1,y1,x2,y2...], should first modify data (as per lars's supggestion), this:

var formattedlinedata = [];  function formatdatapoints(element, index, array) {     // every index (0, 2, 4...)     if (index % 2 === 0){         // ...take current value in array, , next 1         formattedlinedata.push({"x": array[index], "y": array[index + 1]});     } } linedata.foreach(formatdatapoints); 

this create array of objects looks this:

capture of console view

then change line function expect format:

var linefunction = d3.svg.line()     .x(function(d) { return d.x; })     .y(function(d) { return (height - d.y); })     .interpolate("linear"); 

updated fiddle: http://jsfiddle.net/henbox/4e2rkm5d/1/

note - height - d.y because in svg, (0,0) in top-left, whereas assume want count y-axis bottom


Comments

Popular posts from this blog

javascript - Bootstrap Popover: iOS Safari strange behaviour -

Magento/PHP - Get phones on all members in a customer group -

session - Logging Out Using PHP -