Most basic wordcloud in d3.js

Several javascript libraries allow to build wordclouds with d3.js. This post describes the basic usage of d3-cloud. You can see many other examples in the wordcloud section of the gallery. Watch out, wordclouds have many downsides as explained in

Wordcloud section


  • The Html part of the code just creates a div that will be modified by d3 later on.

  • The first part of the javascript code set a svg area. It specify the chart size and its margin. Read more.

  • In this example dummy data are created. It's a vector format. See here to work from a .csv

  • The wordcloud is then drawn thanks to the d3-cloud plugin. The first step is to set the layout. Basically, it runs an algorythm that compute the position of each word.

  • The built object has all the requested features to draw words on by one.

  • See the next post for cusomization
<!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"]

// 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 algorythm to find the position of words that suits your requirements
var layout =
  .size([width, height])
  .words( { return {text: d}; }))
  .on("end", draw);

// This function takes the output of 'layout' above and draw the words
// Better not to touch it. To change parameters, play with the 'layout' variable above
function draw(words) {
      .attr("transform", "translate(" + layout.size()[0] / 2 + "," + layout.size()[1] / 2 + ")")
        .style("font-size", function(d) { return d.size + "px"; })
        .attr("text-anchor", "middle")
        .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