Chat with us, powered by LiveChat

How to Create Word Tree Using JavaScript

October 14th, 2022 by Awan Shrestha

A word tree chart in JavaScriptIt is a pure fact that a graphical or pictorial representation of data, known as a data visualization, conveys information faster than raw data in arrays, spreadsheets, or dense reports. Charts make data easier to understand, which further helps to quickly develop valuable insights. Interesting, right? Now, let’s have a look at one chart type called a word tree and see how to build it with ease.

A word tree is a data visualization form designed to show multiple parallel sequences of words (or phrases) as they appear in a text. Analyzing texts becomes easier with word trees as they display, by means of a branching structure, how selected words are connected to others.

In this tutorial, I will walk you through the process of creating a beautiful word tree chart with JavaScript (HTML5). The text being visualized will be the famous speech “I Have a Dream” by minister and civil rights activist Martin Luther King Jr. Each step will be explained in detail, and you’ll see everything is pretty simple. Sit tight and enjoy the learning!

Word Tree Chart That Will Be Created

Here is how the final word tree chart will look. Keep reading to find out how a visualization like this can be created real quick using JavaScript.

A look at the final JavaScript Word Tree chart that will be built along the tutorial

Building Basic Word Tree with JavaScript

You might have found the concept of a word tree a little complicated. But I assure you that it is no great deal to create such a chart. Here are four basic steps:

  1. Create an HTML page.
  2. Include JavaScript files.
  3. Load the data.
  4. Add some JS code for the chart.

Now, we’ll go through each of these steps.

1. Create an HTML page

The first step is to get a web page for the chart.

Create a basic HTML page. Add a <div> element — it’s where the word tree will be placed. Give it an ID.

Set the width and height parameters to 100% in order to display the chart on the entire screen. Or configure that as per your requirements.

Feel free to add your special touch to the structure.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>JavaScript Word Tree Chart</title>
    <style type="text/css">      
      html, body, #container { 
        width: 100%; 
        height: 100%; 
        margin: 0; 
        padding: 0; 
      } 
    </style>
  </head>
  <body>
    <div id="container"></div>
  </body>
</html>

2. Include JavaScript files

Creating word trees can be very easy when you use a good JavaScript charting library that supports this chart type out of the box. In this tutorial, the process will be demonstrated using AnyChart based on the word tree documentation.

Let’s include the required JS files from the AnyChart CDN (alternatively, you can download them). The core module and word tree module are the scripts needed to create the word tree chart. jQuery will be used to query a text file.

The scripts need to be referenced in the <head> section. The JS code will be placed in the JavaScript tag script that can be put anywhere in the <head> or <body> sections. So our HTML would now look something like this:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>JavaScript Word Tree Chart</title>
    <script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-core.min.js"></script>
    <script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-wordtree.min.js"></script>
    <script src="https://code.jquery.com/jquery-latest.min.js"></script>
    <style type="text/css">      
      html, body, #container { 
        width: 100%; 
        height: 100%; 
        margin: 0; 
        padding: 0; 
      } 
    </style>
  </head>
  <body>
    <div id="container"></div>
    <script>
      // The JS Word Tree chart’s code will be written here.
    </script>
  </body>
</html>

3. Load the data

Now, it’s time to set the data. I have downloaded the speech “I Have A Dream” by Dr. Martin Luther King, Jr. from Marshall University‘s website and created a data file.

To load the data into the JS chart, we will use the jQuery ajax() function as shown in the next step.

4. Add some JS code for the chart

Now, a few lines of JavaScript code are needed to make a functional word tree chart.

First, add the anychart.onDocumentReady() function which wraps up the entire chart code, making sure that the charting will be executed only after the page has loaded completely.

<script>
  anychart.onDocumentReady(function () {
    // The main part of the word tree code will go here.
  }
</script>

Then, load the data as preliminarily explained in the third step.

anychart.onDocumentReady(function () {
  $.ajax("https://gist.githubusercontent.com/awanshrestha/0033cf6344bcda10c242b64fe1d8c2f7/raw/115a11507a1d672fbf651f1bd413963318501010/i-have-a-dream-speech.txt").done(function (text) {
    // The rest of the word tree code will go here.
  });
});

After that, create a word tree chart instance using the wordtree() function of the JS library and pass the text data to it.

var chart = anychart.wordtree(text);

Defining the root word is a significant part of a word tree chart, as it is this root word that branches out to various sentences in the text. For this example, let’s set “I” as the root word.

chart.word("I");

In the end, we give the chart a title, define the container, and display the result.

chart.title("Word Tree of \"I Have a Dream\" Speech by Martin Luther King");
chart.container("container");
chart.draw();

Hurray, it’s done! This is all that is required to create an interactive word tree chart using JavaScript. Such visualization can be embedded into any web page or app and work in any browser.


This JavaScript word tree chart is available on AnyChart Playground with the full code. Feel free to experiment with it right there. The complete word tree code is also placed below, for your convenience.

<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>JavaScript Word Tree Chart</title>
    <script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-core.min.js"></script>
    <script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-wordtree.min.js"></script>
    <script src="https://code.jquery.com/jquery-latest.min.js"></script>
    <style type="text/css">      
      html, body, #container { 
        width: 100%; 
        height: 100%; 
        margin: 0; 
        padding: 0; 
      } 
    </style>
  </head>
  <body>
    <div id="container"></div>
    <script>
      anychart.onDocumentReady(function () {
 
        $.ajax("https://gist.githubusercontent.com/awanshrestha/0033cf6344bcda10c242b64fe1d8c2f7/raw/115a11507a1d672fbf651f1bd413963318501010/i-have-a-dream-speech.txt"
        ).done(function (text) {
 
          // create a word tree chart
          var chart = anychart.wordtree(text);

          // set the root word
          chart.word('I');
 
          // set the chart title
          chart.title("Word Tree of \"I Have a Dream\" Speech by Martin Luther King");

          // set the container id
          chart.container("container");

          // initiate the drawing of the word tree chart
          chart.draw();
 
        }); 
 
      });
    </script>
  </body>    
</html>

This JS-based word tree already looks beautiful. But there is always room for improvement. Using AnyChart, it is easy to modify any aspect of the chart according to your personal preferences. Let’s proceed with customization!

Customizing JavaScript Word Tree Chart

Below, I want to show you how to make some quick changes and improvements to the JS word tree chart:

  1. Customize the fonts.
  2. Modify the connectors.
  3. Change the root word.

A. Customize the fonts

Enhancing the way a text looks is easy with the help of HTML, which can be enabled using the useHtml() function. Let’s customize the word tree’s title like this:

chart
  .title()
  .enabled(true)
  .useHtml(true)
  .text('<span style = "color: #2b2b2b; font-size:20px;">Word Tree: I Have a Dream Speech</span>');

It’s also possible to modify the font settings for the word tree itself using several handy functions:

chart.fontColor("#0daf8d");
chart.fontWeight(500);
chart.fontStyle('italic');
chart.minFontSize(8);
chart.maxFontSize(16);

This is how the word tree looks after the font reconfiguration.


See this JS word tree version on AnyChart Playground.

B. Modify the connectors

The branches that connect one word to another in a word tree chart can also be easily modified according to your preference. I feel the chart looks more organized with straight line connectors. So, why not try them?

Let’s change the shape of the connectors using the curveFactor() function and their length with the length() function. Similarly, its offset and stroke can be customized.

var connectors = chart.connectors();
connectors.curveFactor(0);
connectors.length(100);
connectors.offset(5);
connectors.stroke("1.5 #1976d2");


I have changed it to straight lines, however, if you are good with just changing its curve by a bit, feel free to do that.

You can find this JS word tree version on AnyChart Playground.

C. Change the root word

What if you wish to change the root word? Yeah, you could just set a new one in this part of the JS code:

chart.word("I");

What if you want to change it dynamically from the chart itself? Will it require a complicated code? Not at all! I will show you how to change the root word dynamically in a few simple steps.

Let’s add two buttons. Clicking on them will change the root word to “I” or “This,” respectively. Here’s what goes to the HTML section for that. Add a <div> for the buttons and add the two buttons there. In the buttons, add an onclick attribute, so that when the user clicks on a button, the switchRoot() function gets called (which will be defined in the JS section). Then, pass the desired root word as a parameter to this function.

<div class="button-container">
  <span>Root word: </span>
  <button onclick="switchRoot('I')">I</button>
  <button onclick="switchRoot('This')">This</button>
</div>

You can fine-tune the appearance of the buttons using the CSS. For example:

.button-container{
  padding: 20px 0 0 20px;
  font-family: 'Arial'
}

button{
  border: 1px solid #222222;
  border-radius: 8px;
  color: #222222;
  font-size: 16px;
  font-weight: 600;
  padding: 4px 18px;
  margin-right: 10px;
  cursor: pointer;
}

Now, in the JavaScript part, we create a variable and copy the instance of the word tree chart to it.

let theChart;

anychart.onDocumentReady(function () {
$.ajax( "https://gist.githubusercontent.com/awanshrestha/0033cf6344bcda10c242b64fe1d8c2f7/raw/115a11507a1d672fbf651f1bd413963318501010/i-have-a-dream-speech.txt").done(function (text) {
      
  var chart = anychart.wordtree(text);
  theChart = chart;

Finally, define the switchRoot() function. Pass the root word parameter to it and change the root word inside it using the word() function.

function switchRoot(newWord){
  theChart.word(newWord);
};

Now you see two buttons above the chart, and by clicking on them, you can switch between the root words.


The complete source code for this final version of the JavaScript word tree chart is available below, as well as on AnyChart Playground.

<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>JavaScript Word Tree Chart</title>
    <script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-core.min.js"></script>
    <script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-wordtree.min.js"></script>
    <script src="https://code.jquery.com/jquery-latest.min.js"></script>
    <style type="text/css">      
      html, body, #container { 
        width: 100%; 
        height: 100%; 
        margin: 0; 
        padding: 0; 
      } 
      .button-container{
        padding: 20px 0 0 20px;
        font-family: 'Arial'
      }
      button{
        border: 1px solid #222222;
        border-radius: 8px;
        color: #222222;
        font-size: 16px;
        font-weight: 600;
        padding: 4px 18px;
        margin-right: 10px;
        cursor: pointer;
      }
    </style>
  </head>
  <body>
    <div class="button-container">
      <span>Change Root Word to: </span>
      <button onclick="switchRoot('I')">I</button>
      <button onclick="switchRoot('This')">This</button>
    </div>
    <div id="container"></div>
    <script>

      let theChart;

      anychart.onDocumentReady(function () {
 
        $.ajax( 'https://gist.githubusercontent.com/awanshrestha/0033cf6344bcda10c242b64fe1d8c2f7/raw/115a11507a1d672fbf651f1bd413963318501010/i-have-a-dream-speech.txt'
        ).done(function (text) {
 
          // create a word tree chart
          var chart = anychart.wordtree(text);
          theChart = chart;

          // set the root word
          chart.word('I');
 
          // configure the chart title
          chart
            .title()
            .enabled(true)
            .useHtml(true)
            .text('<span style = "color: #2b2b2b; font-size:20px;">Word Tree of \"I Have a Dream\" Speech by Martin Luther King</span>');

          // configure the font size and color
          chart.fontColor("#0daf8d");
          chart.fontWeight(500);
          chart.fontStyle('italic');
          chart.minFontSize(8);
          chart.maxFontSize(16);
 
          // configure the connectors
          var connectors = chart.connectors();
          connectors.curveFactor(0);
          connectors.length(100);
          connectors.offset(5);
          connectors.stroke("1.5 #1976d2");
 
          // set the container id
          chart.container("container");

          // initiate the drawing of the word tree chart
          chart.draw();
 
        }); 

      });

      // a function to set the root word
      function switchRoot(type) {
        theChart.word(type);
      }

    </script>
  </body>    
</html>

Conclusion

Bravo! You have made it to the end of this tutorial by creating this beautiful interactive word tree chart with JavaScript. I can’t wait to see you creating another word tree following this tutorial and adding your personal touch to it.

Also, have a look at the varieties of chart types available in AnyChart, and try to implement them for data visualization. I am sure it will be fascinating.

Moreover, in case of any queries, please don’t hesitate to reach out to me and drop any questions you have, I will do my best to answer them all. Hope you have a great time creating your own word tree charts!


We want to thank Awan Shrestha for this awesome Word Tree tutorial!

Check out other awesome JavaScript charting tutorials on our blog.

If you have an idea for a guest post, just contact us.



No Comments Yet

*