Drawing simple lines with d3js

I am trying to draw lines with d3js using d3.svg.line () without success.

var line = d3.svg.line() .x(function(d) { return Math.random() * 1000 }) .y(function(d) { return Math.random() * 1000}); svg.selectAll("path") .data([1,2,3,4,5,6]).enter() .append("path") .attr("d", line) # line generator .attr("class", "line") .style("stroke", "black" ); 

I inserted gğıgğı in order to find out if he would give an error, but I was not mistaken. it seems that the functions x and y are not being called. with or without gğıgğı all I could do was create empty path elements.

 <path class="line"></path> 

If I replace the line linear generator with

 "M0,0l100,100" 
Lines

successfully completed.

Sample code is at http://jsfiddle.net/99mnK/1/

What am I doing wrong here?

Edit The working version is at http://jsfiddle.net/99mnK/2/ . It looks like d3.svg.line (). Data expects a 2d data array, e.g.

 [[1,1],[2,2],[3,3],[4,4],[5,5],[6,6]] 

instead

 [1,2,3,4,5,6] 
+4
source share
1 answer

d3.svg.line() by itself is not quite ready to work with selectors. Thus, you should simply call it an array of values, and not pass it as a function to the .attr() function, as you do.

So let's say you have:

 var array = [1,2,3,4,5,6] var line = d3.svg.line() .x(function(d) { return Math.random() * 1000 }) .y(function(d) { return Math.random() * 1000}); 

then, to get a description of a path that has 6 random points, you just need to:

 line(array); 

and to apply it to svg path :

 .append('path') .attr('d', line(array)) 

The reason your edited fiddle works with 2d array binding as it is available is because your line function is called with every subitem of the array:

 .line([1,1]) .line([2,2]) .line([3,3]) 

This explains why you see lines with two points, as opposed to 6 points, as you might expect.

Finally, here is an edited fiddle showing how you could draw 6 paths, as your example might have tried to do: http://jsfiddle.net/mharen/3cv3T/5/ p>

+11
source

All Articles