How to change font size for text shown on arcs in D3Js

Print Friendly, PDF & Email

Have you ever asked how to change the size of the text displayed on elements of a D3JS plot so far? After a bit touch search and discovery, I believe this trick isn’t explicitly addressed in anywhere of D3JS documentation and hasn’t asked in various developers’ communities. Therefore, sharing this experience might be useful for some needing it. Let’s go to see how to do so in 3DJS now.

A Pie Chart Created in D3Js
A Pie Chart Created in D3Js

If you want to change the size of text on D3JS graphs, please add this .style("font-size", "1.5em")to the elements in question.

var gs = svg.selectAll(".arc")
   .data(pie(dataset))
   .enter()
   .append("g")
   .attr("class","arc"); //all arcs

And then adding the following statements

gs.append("text")
  .attr("transform", function (d) {
       return "translate(" + arc.centroid(d) + ")";
  })
  .attr("text-anchor", "middle")
  .attr("fill", "white")
  .attr("font-family", "sans-serif")
  .style("font-size", "1.5em")
  .text(function (d) {
      return d.data[1];
  });

Hope this small tip will help you very much in your work.

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.