Creating Waterfall Chart with JS

March 16th, 2021 by Dilhani Withanage

A Waterfall Chart with JSDo you want to know how to easily add a waterfall chart to a web page or application using JavaScript? This tutorial will make sure you’re prepared to confidently deal with that sort of interactive data visualization development!

Waterfall charts illuminate how a starting value turns into a final value over a sequence of intermediate additions (positive values) and subtractions (negative values). These additions and subtractions can be time-based or represent categories such as multiple income sources and expenditures. In finance, a waterfall chart is often called a bridge; you may have also heard it referred to as a cascade, Mario, or flying bricks chart.

To see waterfall charts in action and learn how to build them with JavaScript (HTML5), we need some interesting real-world data to visualize. In this tutorial, let’s look at the 2020 income statement for Alphabet Inc. (GOOGL), the parent company of Google.

Hence, be with me to reach our target step by step, so in the end, you’ll see how a lot of numbers can be made sense of with real ease when illustrated as a beautiful, interactive, JS waterfall chart. All aboard!

How to Create Basic JS Waterfall Chart

Generally speaking, there are four fundamental steps to take when visualizing any chart in JS:

  • Step 1: Create an HTML page.
  • Step 2: Reference all necessary JavaScript libraries.
  • Step 3: Load the dataset required to be visualized.
  • Step 4: Write some JS charting code.

Let’s follow these steps now and build a cool JavaScript waterfall chart based on that approach. In reality, it’s all quick.

Step 1: Create an HTML page

The first thing is to make an HTML page where the waterfall chart can be rendered.

<!DOCTYPE html>
<html>
  <head>
    <title>Waterfall Chart Example</title>
    <style>
      html, body, #WaterfallContainer {
        width: 100%;
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <div id="WaterfallContainer">
      // Place the waterfall chart here.
    </div>
  </body>
</html>

The HTML page created as shown above has a title included in the <title> tag. The styling sheet is determined in <style>. Feel free to customize these according to your preference.

In the <body> section, there is a <div> element that will be used as a container for the waterfall chart. It should have an id so we can easily refer to it later. In this case, its id is set as WaterfallContainer.

Step 2: Reference all necessary JavaScript libraries

Second, we need to connect all relevant JS scripts that will be used to generate the waterfall chart. The URLs go in the <script> tag inside of the <head> section. For this tutorial, I have chosen AnyChart‘s JavaScript charting library. It’s powerful, flexible, and easy-to-use, making charts promptly visualized on your web pages. The process, however, is pretty universal.

AnyChart is modular, which means you don’t have to load the full library when you only need some of its charts and features. To create a waterfall chart, we need just the core library module, which is required for all types of charts, and the dedicated “Waterfall” module.

<!DOCTYPE html>
<html>
  <head>
    <title>Waterfall Chart Example</title>
    <script src="https://cdn.anychart.com/releases/8.9.0/js/anychart-core.min.js"></script>
    <script src="https://cdn.anychart.com/releases/8.9.0/js/anychart-waterfall.min.js"></script>      
    <style>
      html, body, #WaterfallContainer {
        width: 100%;
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <script>
      // Place the waterfall chart here.
    </script>
  </body>
</html>

Step 3: Load the dataset required to be visualized in a waterfall chart

So, in order to show you the beauty and mission of waterfall charts, I needed a dataset where the initial value is impacted by a series of intermediate values, positive and negative.

I decided to look at the annual income statement of Alphabet Inc. for the year 2020. Here’s the dataset I prepared for this JS waterfall chart tutorial based on it:

Breakdown USD in millions
Total Revenue 182,527
Cost of Revenue (84,732)
Gross Profit 97,795
Operating Expenses (56,571)
Operating Income 41,224
Other Income 8,583
Other Expenses (1,725)
Income Before Taxes 48,082
Provision for Taxes (7,813)
Net Income 40,269

 
Now that we’ve got the data, let’s transmute it into an array of objects:

var data = [
  { x: 'Total Revenue', value: 182527 },
  { x: 'Cost of Revenue', value: -84732 },
  { x: 'Gross Profit', isTotal: true },
  { x: 'Operating Expenses', value: -56571 },
  { x: 'Operating Income', isTotal: true },
  { x: 'Interest Income', value: 8583 },
  { x: 'Other Expenses', value: -1725 },
  { x: 'Income Before Taxes', isTotal: true },
  { x: 'Provision for Taxes', value: -7813 },
  { x: 'Net Income', isTotal: true }
];

If you carefully look at the snippet above, there is a keyword called isTotal. It is used to show totals, and basically when you need to get the cumulative value of a series of additions and subtractions, just include it with the value true. That’s right, you don’t even have to calculate anything as the library does that for you, on the fly.

Step 4: Write the JS waterfall charting code

So far, everything is in place and we are literally one step to the waterfall chart visualization. With just a few more lines of JavaScript code, it will be ready for you to check out and even integrate it anywhere for further analytics.

Everything we’ve prepared earlier needs to be put inside the anychart.onDocumentReady() function that must be placed in the <script> tag residing in the <body> section of our HTML page.

<script>
  anychart.onDocumentReady(function() {
    // The entire JS code of the waterfall chart will be here.
  });
</script>

Next, simply command to create a waterfall chart and feed it the dataset as we shaped it in Step 3:

var chart = anychart.waterfall(data);

Shall we set the main title for our chart?

chart.title('Income Statement for Alphabet Inc. (GOOGL), 2020');

Ultimately, let’s draw the resulting JS waterfall chart in the container we set in Step 1:

// set the container id for the waterfall chart
chart.container('WaterfallContainer');

// draw the resulting chart
chart.draw();	

Let’s have a look at the result below! It’s a basic interactive JavaScript-based waterfall chart visualizing Google’s 2020 income statement, which we’ve just created in just a very few lines of code.


For your convenience, the complete code is below and you are welcome to inspect it on AnyChart Playground. Keep reading though as customizations are approaching!

<!DOCTYPE html>
<html>
  <head>
    <title>Waterfall Chart Example </title>
    <script src="https://cdn.anychart.com/releases/8.9.0/js/anychart-core.min.js"></script>
    <script src="https://cdn.anychart.com/releases/8.9.0/js/anychart-waterfall.min.js"></script>      
    <style>
      html, body, #WaterfallContainer {
        width: 100%;
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <script>

      anychart.onDocumentReady(function () {

        // set the data
        var data = [
          { x: 'Total Revenue', value: 182527 },
          { x: 'Cost of Revenue', value: -84732 },
          { x: 'Gross Profit', isTotal: true },
          { x: 'Operating Expenses', value: -56571 },
          { x: 'Operating Income', isTotal: true },
          { x: 'Interest Income', value: 8583 },
          { x: 'Other Expenses', value: -1725 },
          { x: 'Income Before Taxes', isTotal: true },
          { x: 'Provision for Taxes', value: -7813 },
          { x: 'Net Income', isTotal: true }
        ];

        // create a waterfall chart with the data
        var chart = anychart.waterfall(data);

        // set the chart title
        chart.title('Income Statement for Alphabet Inc. (GOOGL), 2020');

        // set the container id for the waterfall chart
        chart.container('WaterfallContainer');
          
        // draw the resulting chart
        chart.draw();

      });

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

Customizing JS Waterfall Chart

I believe you agree that the basic JS waterfall chart we’ve built already looks good. But there’s always room for improvement, isn’t it?

When it comes to customization, it’s essential that the data visualization library you are using be flexible enough to let you implement what you want in a simple manner. For example, now I will show you how, with hardly more than a handful of intuitive effort, we can make our waterfall chart more engaging and artistic.

Work with the axes

Let’s start with adding the $ sign before the values to make it absolutely clear those sums are in USD:

chart.yAxis().labels().format('${%Value}');

We can also add a title for the Y-axis, specifying that the figures are provided in millions:

chart.yAxis().title('Amount (in millions)');

The X-axis labels (category names) are quite long. Let’s put them vertically. Just set the X-axis label rotation like that:

chart.xAxis().labels().rotation(-90);

Look what we’ve got! (See this customized JS waterfall chart on AnyChart Playground.)


Style the connectors

Now, let’s modify the waterfall chart’s connectors, the lines drawn between the columns.

Use the connectorStroke() method to adjust the stroke of the connectors. Its detailed parameter explanation can be found in the API Reference.

chart.connectorStroke("#ff6666", 2, "2 2", "round");

Check out the result below. (See this customized JS waterfall chart with newly designed connectors on AnyChart Playground.)


Customize the waterfall column labels using HTML

It can be great to configure HTML formatted labels in the waterfall chart. To enable HTML, just set the parameter of the useHtml() method as true. Then simply add the necessary HTML tags and they will work.

// enable HTML for the labels
chart.labels().useHtml(true);         

// customize the labels
chart.labels().format(function() {
  if (this.isTotal)
    return "<span style="color: #dd2c00; font-weight: bold;">" +
      this.absolute + "</span>";
  return this.diff;
});

According to the above configuration, the chart.labels().format() method returns a <span> element with special HTML-based formatting for the column labels displaying totals.


You can see that the column labels, which indicate total values, have been formatted with bold red letters. (See this customized JS waterfall chart with HTML formatted labels on AnyChart Playground.)

Change the appearance of the waterfall columns

Instead of using default colors, this is high time to personalize the column appearances and make them elegant by giving a touch of some magnificent colors.

To change the design that way, we need an explicitly defined series. So, in this case, we create a waterfall chart, then configure a series, and then feed the data:

// create a waterfall chart
var chart = anychart.waterfall();

// create a series and set the data
var series = chart.waterfall(data);

The appearance of the waterfall chart columns can be configured for three different states: normal(), hovered(), and selected(). To change the look of the columns which represent totals, these methods can be combined with such methods as fill() to set the fill, hatchFill() to set the hatch fill, and stroke() to set the stroke.

Taking the same approach, we can adjust the appearance of falling and rising columns as shown below.

// configure the visual settings of the total columns
series.normal().fill("#ff6666", 0.3);
series.normal().hatchFill("forward-diagonal", "#ff6666", 0.5, 10);
series.normal().stroke("#ff6666");
series.hovered().fill("#ff6666", 0.1);
series.hovered().hatchFill("forward-diagonal", "#ff6666", 0.5, 10);
series.hovered().stroke("#ff6666", 2);
series.selected().fill("#ff6666", 0.5);
series.selected().hatchFill("forward-diagonal", "#ff6666", 0.5, 10);
series.selected().stroke("#ff6666", 4);
 
// configure the visual settings of the falling columns
series.normal().fallingFill("#00cc99", 0.3);
series.normal().fallingStroke("#00cc99", 1, "10 5", "round");
series.hovered().fallingFill("#00cc99", 0.1);
series.hovered().fallingStroke("#00cc99", 2, "10 5", "round");
series.selected().fallingFill("#00cc99", 0.5);
series.selected().fallingStroke("#00cc99", 4, "10 5", "round");
 
// configure the visual settings of the rising columns
series.normal().risingFill("#0066cc", 0.3);
series.normal().risingStroke("#0066cc");
series.hovered().risingFill("#0066cc", 0.1);
series.hovered().risingStroke("#0066cc", 2);
series.selected().risingFill("#0066cc", 0.5);
series.selected().risingStroke("#0066cc", 4);

Now the waterfall chart looks exquisite with such soft colors, right? Do the changes according to your preference and make your final output even more elegant! (See this final customized JS waterfall chart on AnyChart Playground.)


So, what does the waterfall chart tell us? The visualization above shows how Alphabet’s total revenue of $182.5 billion turns into a net income of almost $40.3 billion, representing the major flows of income and expense in the 12 months of 2020. Feel free to explore and analyze!

Conclusion

Instead of reading and going through raw numbers, isn’t it a better idea to use a cool waterfall chart and get valuable observations without much effort?

You can also visualize multiple series. Go through the Waterfall Chart Documentation and delve into more details of what else can be done and how.

Good luck with interactive data visualization with JavaScript, in waterfall charts and beyond.


We at AnyChart are glad to thank Dilhani Withanage for writing this stunning JS Waterfall Chart tutorial.

If you want to create an interesting guest post for our blog, get in touch.


Check out other JavaScript charting tutorials.


No Comments Yet

*