Draw line with d3.js using separate, fixed x & y input arrays

d3.js, svg

Solution

Based on Elijah's spot on remark about `d3.svg.line`, I think it is hard to go about this without putting the array as expected by this function. So:

var xy = [];
for(var i=0;i<xdata.length;i++){
   xy.push({x:xdata[i],y:ydata[i]});
}

I made other changes regarding `.domain` and the `slice` function per se. Here is a FIDDLE with the results of my effort.

Problem

I have separate x and y arrays and want to connect the dots using a line path. This seems to be about the simplest possible example but I don't quite grok the writing the function. Here is my code: ``` <!DOCTYPE html> <meta charset="utf-8"> <body> <script src = "http://d3js.org/d3.v3.min.js"> </script> <script> var margin = {top: 20, right: 20, bottom: 20, left: 20}, width = 600 - margin.left - margin.right, height = 270 - margin.top - margin.bottom; var xdata = d3.range(20); var ydata = [1, 4, 5, 9, 10, 14, 15, 15, 11, 10, 5, 5, 4, 8, 7, 5, 5, 5, 8, 10]; var xscl = d3.scale.linear() .domain(d3.extent(xdata)) .range([0, width]) var yscl = d3.scale.linear() .domain(d3.extent(ydata)) .range([height, 0]) var slice = d3.svg.line() .x(function(d) { return xscl(xdata[d]);}) .y(function(d) { return yscl(ydata[d]);}) var svg = d3.select("body") .append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) svg.append("path") .attr("class", "line") .attr("d", slice) </script> </body> ``` But it returns an error `Uncaught TypeError: Cannot read property 'length' of undefined`, so clearly the function returned by `d3.svg.line()` doesn't have the right form. What's wrong? I pray not a typo!

Original source