Contents

How to Draw a Circle in D3

Contents

Hi! In this article we will see the attributes needed to draw a circle and how to add it in your D3 project.

Let’s do it! If you get stuck, feel free to send me a DM.

First, make sure you have an SVG object define in your script:

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

You can get information on SVG just here:

Then use the append function in D3 to add a circle object:

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

Now precise the attributes of your circle. First, let’s define the position of the circle:

1
2
circle.attr("cx", 50);
circle.attr("cy", 60);

Be aware that the cx and cy value correspond to the position of the center of your circle. That is explain why the attribute’s names started with a “c”. Note also that the position is define from the up let corner of the SVG object.

Now that we have precised the position of our circle, we need to define his radius:

1
2
circle.attr("r", 40);

With the snippet above, we set the radius of the circle with 40 pixels.

Finally, the most interesting part for me: make it colorful. To do it, just add the snippet in your file:

1
2
circle.attr("fill", "red");

This will fill the circle with red. You can use strings to define the color or you can use the hex definition.

So now, as I used to do, we will chain the attribute of the circle. Therefore, you can just add a circle in one line with:

1
const circle = svg.append("circle").attr("cx", 50).attr("cy", 60);attr("r", 40).attr("full", "red");

This will give the result below:

I hope you enjoyed this post!