Contents

How to Draw a Line in D3.js?

Contents

In this article, I will show you how to draw lines in D3 by using attributes. It’s a very simple object to master and you will see in futures posts that it could be very useful to make a plot.

First let’s define the svg object as usual with the D3 select function:

1
const svg = d3.select("#mysvg").append("svg").attr("width", 100).attr("height", 100);

Now we can add a line to this svg object:

1
const line = svg.append("line");

A line as you know is define with two points, in D3 too. Therefore we just have to add the x and y position of this two points:

1
2
3
4
line.attr("x1", 15);
line.attr("y1", 47);
line.attr("x2", 99);
line.attr("y2", 15);

So now we need to color the line. Just add the attribute “stroke” to do it.

line.attr("stroke", "green");

Finally, just define the width of this stroke:

line.attr("stroke-wdith", 7);

The final result should look like this:

You can use the chaining method to simplify your code:

1
2
3
4
5
6
7
const line = svg.append("line")
      .attr("x1",15)
      .attr("y1", 47)
      .attr("x2",99)
      .attr("y2", 15)
      .attr("stroke", "green")
      .attr("stroke-width", 7);

As you can see, it’s very simple to draw a line in D3 and there is no tricky parts at first sight but if you have any question you can ask me in DM. See you!