Contents

How to Add Texts in D3.js?

Contents

Like shapes, texts are Scalable Vector Graphics in D3.

In this article, I want to show you how to use text in your D3 projects. We will see the attributes you should know to manage the position, the color and the content of a text.

First, just define a text object like this:

const text = svg.append("text");

We use the append function of D3 to add a text to the whole svg in your window. Remember that we have to define an SVG object at the top of the document.

Then, precise the position of this text with the attr function of D3:

text.attr("x", 15); text.attr("y", 15);

Note that text position are define with the top left corner of the text.

Now, we can add the font-size and the color:

text.attr("font-size", 20); text.attr("fill", "red");

Remember that all integer value are in pixel and that you can define a color with his hex definition.

Finally, the most important, the content. You just need to add a .text() method to your text object and to precise the content in argument:

text.text("My text");

Now, let me show you how to simplify all this lines by just one using the chaining method:

1
2
3
4
5
6
const text = svg.append("text")
      .attr("x", 15)
      .attr("y", 15)
      .attr("font-size", 20)
      .attr("fill", "red")
      .text("My text");

The result should look like this:

My text

That’s it! Texts are not complicated objects but are very useful when we need to add a legend (I will post about it later).

I hope you enjoyed this article. Do not hesitate to send me a DM if you have questions. See you!