Chat with us, powered by LiveChat

How to Create JavaScript Word Cloud Chart — Tutorial for Web Developers

April 30th, 2019 by Irina Maximova

Tutorial on how to create a JavaScript word cloud chart and customize it, for front-end web developers
Wondering how to make a beautiful interactive Word Cloud using JS? Then you’re in the right place! In this data visualization tutorial, I’ll guide you through the entire development process, demonstrating it’s easier to create a JavaScript word cloud chart for an HTML5 app or web page than you might think!

Also known as tag clouds, word clouds represent a popular visual technique designed to reveal how often tags (or basically, any words) are mentioned in a given text body. Essentially, the word cloud chart type leverages diverse colors and sizes to display at a glance different levels of relative prominence.

Now that we’ve got an idea of what a word cloud is, let’s get down to learning how to quickly code one using JavaScript!

Building Basic JavaScript Word Cloud

Generally speaking, there are four basic steps to create a chart of any type using JavaScript. Just follow them, and it won’t take you long to make your text data visualization look like this:


1. Create an HTML page

First of all, create an HTML page where your JavaScript word cloud chart will appear. It has to be as follows:

<!DOCTYPE html>
<html>
  <head>
    <title>JavaScript Tag Cloud Chart</title>  
    <style>
      html, body, #container {
      width: 100%;
      height: 100%;
      margin: 0;
      padding: 0;
      }
    </style>    
  </head>
  <body>
    <div id="container"></div>
  </body>
</html>

The container that you see in the <body> section is intended for your future chart. The width and height parameters are responsible for the chart size, and you can specify them in percentages or in pixels to make the chart fill as much page space as you want.

2. Reference all necessary files

Then, add the necessary AnyChart JavaScript charting library links into the <head> section in the <script> tags:

<!DOCTYPE html>
<html>
 <head>
  <title>JavaScript Tag Cloud Chart</title>
  <script src="https://cdn.anychart.com/releases/v8/js/anychart-base.min.js"></script>
  <script src="https://cdn.anychart.com/releases/v8/js/anychart-tag-cloud.min.js"></script>
  <style>
    html, body, #container {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
    }
  </style> 
 </head>
  <body>
   <div id="container"></div>
    <script>
        <!-- chart code will be here -->
    </script>
  </body>
</html>

3. Put together the data

The most valuable part of any chart is data. So you should always carefully choose the chart type depending on exactly what you want to visualize and for what purpose. Visit Chartopedia, a handy tool that will tell you more about each chart type and how to use one.

In the present case, a tag (word) cloud chart will be used to demonstrate the 15 most spoken languages. Go to Wikipedia: List of languages by total number of speakers and obtain the data from there:

Language Number of speakers Family
Mandarin Chinese 1.09 billion Sino-Tibetan
English 983 million Indo-European
Hindustani 544 million Indo-European
Spanish 527 million Indo-European
Arabic 422 million Afro-Asiatic
Malay 281 million Austronesian
Russian 267 million Indo-European
Bengali 261 million Indo-European
Portuguese 229 million Indo-European
French 229 million Indo-European
Hausa 150 million Afro-Asiatic
Punjabi 148 million Indo-European
Japanese 129 million Japonic
German 129 million Indo-European
Persian 121 million Indo-European

The magic is that all the tags in a word cloud chart will get their size and color automatically after you write the values and put the languages in categories in the data object:

// set the data
var data = [
    {"x": "Mandarin chinese", "value": 1090000000, category: "Sino-Tibetan"},
    {"x": "English", "value": 983000000, category: "Indo-European"},
    {"x": "Hindustani", "value": 544000000, category: "Indo-European"},
    {"x": "Spanish", "value": 527000000, category: "Indo-European"},
    {"x": "Arabic", "value": 422000000, category: "Afro-Asiatic"},
    {"x": "Malay", "value": 281000000, category: "Austronesian"},
    {"x": "Russian", "value": 267000000, category: "Indo-European"},
    {"x": "Bengali", "value": 261000000, category: "Indo-European"},
    {"x": "Portuguese", "value": 229000000, category: "Indo-European"},
    {"x": "French", "value": 229000000, category: "Indo-European"},
    {"x": "Hausa", "value": 150000000, category: "Afro-Asiatic"},
    {"x": "Punjabi", "value": 148000000, category: "Indo-European"},
    {"x": "Japanese", "value": 129000000, category: "Japonic"},
    {"x": "German", "value": 129000000, category: "Indo-European"},
    {"x": "Persian", "value": 121000000, category: "Indo-European"}
  ];

4. Write the JS word cloud chart code

Now, add the anychart.onDocumentReady() function to be executed when the page is ready:

<script>
anychart.onDocumentReady(function() {
    // code to create a word cloud chart will be here
});
</script>

After that, add the data into the function, create the tag cloud chart, set its title and legend, and just command to display it:

anychart.onDocumentReady(function() {
  var data = [
    {"x": "Mandarin chinese", "value": 1090000000, category: "Sino-Tibetan"},
    {"x": "English", "value": 983000000, category: "Indo-European"},
    {"x": "Hindustani", "value": 544000000, category: "Indo-European"},
    {"x": "Spanish", "value": 527000000, category: "Indo-European"},
    {"x": "Arabic", "value": 422000000, category: "Afro-Asiatic"},
    {"x": "Malay", "value": 281000000, category: "Austronesian"},
    {"x": "Russian", "value": 267000000, category: "Indo-European"},
    {"x": "Bengali", "value": 261000000, category: "Indo-European"},
    {"x": "Portuguese", "value": 229000000, category: "Indo-European"},
    {"x": "French", "value": 229000000, category: "Indo-European"},
    {"x": "Hausa", "value": 150000000, category: "Afro-Asiatic"},
    {"x": "Punjabi", "value": 148000000, category: "Indo-European"},
    {"x": "Japanese", "value": 129000000, category: "Japonic"},
    {"x": "German", "value": 129000000, category: "Indo-European"},
    {"x": "Persian", "value": 121000000, category: "Indo-European"}
  ];

 // create a tag (word) cloud chart
  var chart = anychart.tagCloud(data);

   // set a chart title
  chart.title('15 most spoken languages')
  // set an array of angles at which the words will be laid out
  chart.angles([0])
  // enable a color range
  chart.colorRange(true);
  // set the color range length
  chart.colorRange().length('80%');

  // display the word cloud chart
  chart.container("container");
  chart.draw();
});

The JavaScript word (tag) cloud chart code should be put in the <script> tag from the second step. And that’s it!

Yay! You did it! Check out the beautiful JS word cloud sample you’ve made:


Customize Word Cloud Chart Appearance

If you want to change how your JavaScript word cloud chart look, you can easily modify it. Visit the Word Cloud Chart settings and Word Cloud Chart gallery pages to see the instruction on and examples of how it can be done.

In the meantime, let’s makes some visual changes to the tag cloud built along the tutorial.

Tooltips in a word cloud

You must have noticed that in the data object, the values are in millions and billions. But it may be hard to clearly perceive such long numbers in a visual way. Therefore, it would be good to properly configure the chart tooltips with the help of the formatting parameters list:

// format the tooltips
var formatter = "{%value}{scale:(1)(1000)(1000)(1000)|( dozen)( thousand)( million)( billion)}";
var tooltip = chart.tooltip();
tooltip.format(formatter);

Now the JS word cloud sample tooltips read better, don’t they?


Angles of the tags

If you want your JavaScript word cloud to look sort of more сhaotic, you can simply change the angles at which the tags are arranged. For example:

chart.angles([0, -45, 90])

And the JS word cloud chart sample becomes a little bit wild:


Word cloud interactivity

You may also want to link tags to some web pages. If so, use the listen() method to add an event listener to your word cloud chart. In the given case, clicking on a word will lead to its Wikipedia page opening, which means you will be able to find more information about every language:

// add an event listener
chart.listen("pointClick", function(e){
  var url = "https://en.wikipedia.org/wiki/" + e.point.get("x");
  window.open(url, "_blank");
});

Here is your final interactive JS word cloud chart:


Conclusion

You see there is nothing difficult in creating beautiful interactive JavaScript word cloud charts for web pages and applications, in particular using the AnyChart JS (HTML5) charting library for data visualization.

For more information, check the official AnyChart JS Charts website. The Chart Documentation and Chart API Reference sections will help you make and tune your JavaScript charts in a way you prefer, and you can freely play with the code of the charts on the Chart Playground.

You are also welcome to check out the other basic JavaScript chart tutorials on our blog.

Now it’s time for your questions! Feel free to ask them in the comments below or by contacting our Support Team.


Comments (8)

*

alaa    24th Nov 22 12:16 am

how can add a mask and insert words in it

  1. Reply
  2. Link
AnyChart Team    25th Nov 22 4:41 pm

Hi, sorry, there is no such option at the moment.
Everything else: https://docs.anychart.com/Basic_Charts/Word_Tree

  1. Reply
  2. Link
Rajesh    23rd Mar 22 10:32 am

Its really nice.
But How to hide legend ??

  1. Reply
  2. Link
AnyChart Team    24th Mar 22 10:46 pm

Hi Rajesh. Glad you like it, thanks. What you mean is likely to be a color range, a special interactive element representing the color scale; simply remove the following line from the code and it will disappear.

chart.colorRange(true);
  1. Reply
  2. Link
Prabhat Pal    2nd Jun 20 9:58 am

Dear Team,
Thanks for share awesome chart.
Once question, how to hide tool-tip?

  1. Reply
  2. Link
AnyChart Team    3rd Jun 20 5:00 pm

Hello, we are glad you’ve found our JS tag cloud tutorial helpful. By default, the tooltip is shown when a point is hovered over. To disable it, add:

chart.tooltip(false);

To learn more about working with the tooltip, check the tooltip documentation.

Hope this helps.

  1. Reply
  2. Link
AlOtaibi    14th Jan 20 11:48 am

hello , thank you for sharing, can you please check my below javascript as i am trying to generate an output word by word instead of line by line.
i tried to add split function but seems i missed the right place.

can you please help me
your answer is highly appreciated.

// Javascript Panel
// generateChart is a required function which will be called to generate your JS chart
generateChart = function (options) {
// Use require to load the javascript libraries you need
require([‘d3_3.5.17/d3_3.5.17.min.js’, ‘cloud.js’], function (d3, cloud) {
// debugger; This will trigger a breakpoint in your browser debugger so you can debug your javascript

var $chartDrawDiv = $(options.divSelector);
$chartDrawDiv.html(

);

var data = options.dataset.data;

//change data.camp_name to properly column name
// var nameColumn = data.loh;
var nameColumn = data.desc; // this column contains 100 line and each line contains sentence

var countColumn = data.inc; // contains number of repeated.

var countMax = d3.max(countColumn, function (d) { return parseInt(d.raw_data) });
var sizeScale = d3.scale.linear().domain([0, countMax]).range([10, 100])
var fill = d3.scale.category20();
var neodata = { name_Column: [], count_Column: [] };
var data_names = [];
var data_counts = [];

//for excepting formatted data
var nC = nameColumn;
nC.forEach(function (key) {
data_names.push(key.raw_data);
});

var cC = countColumn;
cC.forEach(function (key) {
data_counts.push(parseInt(key.raw_data));
});
neodata.name_Column = data_names;
//neodata.count_Column = data_counts;

var words = neodata.name_Column.map(function (d) {
return {
text: d
};
});

for (var i = 0; i < data_counts.length; i++) {
words[i].size = sizeScale(data_counts[i]);
}
var random = d3.random.irwinHall(2)
var layout = cloud()
.size([600, 600])
.words(words)
.padding(1)
// .rotate(function() { return ~~(Math.random() * 2) * 90; })
.rotate(function () { return Math.round(1 – random()) * 60; })// set the angle
.font("Impact")
.fontSize(function (d) { return d.size; })
.on("end", draw);

layout.start();

function draw(words) {
d3.select("svg1").append("svg")
.attr("width", layout.size()[0])
.attr("height", layout.size()[1])
.append("g")
.attr("transform", "translate(" + layout.size()[0] / 2 + "," + layout.size()[1] / 2 + ")")
.selectAll("text")
.data(words)
.enter().append("text")
.style("font-size", function (d) { return d.size + "px"; })
.style("font-family", "Impact")
.style("fill", function (d, i) { return fill(i); })
.attr("text-anchor", "middle")
.attr("transform", function (d) {
return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
})
.text(function (d) { return d.text; });
}
});
};

  1. Reply
  2. Link
AnyChart Team    16th Jan 20 10:14 am

Hello. You are trying to use a different JavaScript charting library. Feel free to try our way described in this tutorial, which is generally easier, and then you are welcome to ask our Support Team for a help if you get any questions: support@anychart.com; https://www.anychart.com/support. Thank you.

  1. Reply
  2. Link