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.
<div id="svgpathSVGdata"></div>
<script type="text/javascript">
var divElem = d3.select("#svgpathSVGdata");
var svgcanvas = divElem.append("svg:svg")
.attr("width", 200)
.attr("height", 200);
// (1) Specifying path data the SVG way
svgcanvas.append("svg:path")
.attr("d","M 0 60 L 50 110 L 90 70 L 140 100")
.style("stroke-width", 2)
.style("stroke", "steelblue")
.style("fill", "none");
</script>
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.
<script type="text/javascript">
var divElem2 = d3.select("#svgpathD3data");
svgcanvas2 = divElem2.append("svg:svg")
.attr("width", 200)
.attr("height", 200)
// (2) Creating path using D3 path data generators
// Specify the path points
pathinfo = [{x:0, y:60},
{x:50, y:110},
{x:90, y:70},
{x:140, y:100}];
// Specify the function for generating path data
var d3line2 = d3.svg.line()
.x(function(d){return d.x;})
.y(function(d){return d.y;})
.interpolate("linear");
// "linear" for piecewise linear segments
// Creating path using data in pathinfo and path data generator
// d3line.
svgcanvas2.append("svg:path")
.attr("d", d3line2(pathinfo))
.style("stroke-width", 2)
.style("stroke", "steelblue")
.style("fill", "none");
</script>
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