Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing simple lines with d3js

Tags:

svg

line

d3.js

I'm trying to draw lines with d3js using d3.svg.line() with no 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've inserted gğıgğı on purpose to see whether it will give an error but i didn'get any error. seems that x and y functions are not called. with or without gğıgğı all i managed to do is create empty path elements.

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

If i replace line generator "line" with

"M0,0l100,100"

lines are succesfully drawn.

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

What am i doing wrong here?

Edit A working version is at http://jsfiddle.net/99mnK/2/ . It seems that d3.svg.line().data expects a 2d data array such as

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

instead of

[1,2,3,4,5,6]
like image 408
altunyurt Avatar asked Dec 20 '22 13:12

altunyurt


1 Answers

d3.svg.line() by itself is not quite made to work with selectors. As such, you're supposed to just call it with an array of values – rather than passing it as a function into .attr() function as you're doing.

So, 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 path description that has 6 random points, you simply need:

line(array);

and, to apply it to an svg path:

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

The reason your edited fiddle works, with a 2d array binding as you have it, is because your line function is being called with each sub-element of the array:

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

That explains why you're seeing lines drawn with just 2 points, as opposed to 6 points, as you might have expected.

Finally, here's an edited fiddle showing how you might draw 6 paths, as your example was maybe attempting to do: http://jsfiddle.net/mharen/3cv3T/5/

like image 76
meetamit Avatar answered Mar 07 '23 17:03

meetamit