Custom wordcloud in d3.js

The previous post described how to build a very basic wordcloud with the d3-cloud javascript plugin. This post shows how to apply customization like colors, font, angle, size and more.

Wordcloud section


  • See the previous post for a very basic wordcloud with the d3-cloud plugin.

  • This post show a few options to add color, orientation, font and more to the text.

  • Note that options that are the same for every word can be passed directly in the draw function

  • However, options that vary must first be given in the layout call. They will be then available in the words object, and must thus be called again in the draw function.

<!DOCTYPE html>
<meta charset="utf-8">

<!-- Load d3.js -->
<script src=""></script>

<!-- Load d3-cloud -->
<script src=""></script>

<!-- Create a div where the graph will take place -->
<div id="my_dataviz"></div>


// List of words
var myWords = ["Hello", "Everybody", "How", "Are", "You", "Today", "It", "Is", "A", "Lovely", "Day", "I", "Love", "Coding", "In", "My", "Van", "Mate", "Peace", "Love", "Keep", "The", "Good", "Work", "Make", "Love", "Not", "War","Surfing","R", "R",
   "Data-Viz","Python","Linux","Programming","Graph Gallery","Biologie", "Resistance",
   "Computing","Data-Science","Reproductible","GitHub","Script", "Experimentation","Talk","Conference","Writing",
   "Programming","Wheat","Virus","Genotyping","Work","Fun","Surfing","R", "R",

// set the dimensions and margins of the graph
var margin = {top: 10, right: 10, bottom: 10, left: 10},
    width = 450 - margin.left - margin.right,
    height = 450 - - margin.bottom;

// append the svg object to the body of the page
var svg ="#my_dataviz").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + + margin.bottom)
          "translate(" + margin.left + "," + + ")");

// Constructs a new cloud layout instance. It run an algorithm to find the position of words that suits your requirements
// Wordcloud features that are different from one word to the other must be here
var layout =
  .size([width, height])
  .words( { return {text: d}; }))
  .padding(5)        //space between words
  .rotate(-45)       // rotation angle in degrees
  .fontSize(20)      // font size of words
  .on("end", draw);

// This function takes the output of 'layout' above and draw the words
// Wordcloud features that are THE SAME from one word to the other can be here
function draw(words) {
      .attr("transform", "translate(" + layout.size()[0] / 2 + "," + layout.size()[1] / 2 + ")")
        .style("font-size", 20)
        .style("fill", "#69b3a2")
        .attr("text-anchor", "middle")
        .style("font-family", "Impact")
        .attr("transform", function(d) {
          return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
        .text(function(d) { return d.text; });

Related blocks →

  • Example section of d3-cloud documentation - by Jason Davies