Saturday, January 14, 2012

Drawing an SVG path using D3.js

In this post I show two ways of creating a simple SVG path using D3.js:

Method 1: the path data is specified in the same way as when using raw SVG (see here for more information).

Method 2: the path data is specified using path data generator method d3.svg.line() provided by D3.js

Method 1

I am assuming that you have the skeleton HTML file with link to d3.js. Add the following script to that HTML file. Open the file in the browser and you should see:

Method 2

The same path as you see above is drawn here. But instead of specifying the path as a string, as done above, I have used the d3.svg.line() method to generate it from the given set of points. As we expected, this code also gives:

4 comments:

  1. Thank you, this is just what I was looking for.

    ReplyDelete
  2. Thank you, I was struggling with getting the color right. Setting "fill" = "none" did solve the problem :)

    ReplyDelete
  3. Very helpful, thanks.

    ReplyDelete
  4. How would you do to add a label to the path ? I can't solve this problem..

    ReplyDelete