How To Create Sankey Chart in JS (Titanic Survivors)
Tags: javascript, webdev, programming, datascience
Published: 2022-05-26 23:06:57

Would you like to learn how to quickly create a really cool chart called a Sankey diagram? You’re in the right place! Together, we will build an elegant [Sankey chart](https://www.anychart.com/chartopedia/chart-type/sankey-diagram/) using JavaScript, and then you’ll be able to produce such data visualizations by yourself with no hassle at all.

Depicting the flow of values from one set to another, Sankey diagrams are ideal when you need to graphically represent a many-to-many mapping between two domains or multiple paths through a number of stages. So, competence in making them will be a great addition to the skill set of anyone dealing with [data visualization](https://www.anychart.com/blog/2018/11/20/data-visualization-definition-history-examples/) design and development.

110 years after it sank on April 15, 1912, the [Titanic](https://www.anychart.com/blog/2018/11/20/data-visualization-definition-history-examples/) still holds us in its thrall, piquing people’s imagination. Now, we will use the JS Sankey diagramming technique to look at its passengers and crew and find out who survived and perished based on gender, age, and ticket class. Follow along!

## Sankey Diagram Preview

Take a glance at the Sankey diagram we will have built by the end of the tutorial:

![A Sankey diagram built with JavaScript HTML5, visualizing the destiny of the passengers and the crew of the Titanic](https://www.anychart.com/blog/wp-content/uploads/2022/05/sankey-diagram.gif)

Now, the journey begins — read on to learn how to build Sankey charts like this using pure JavaScript!

## Building a Basic JS Sankey Diagram

A Sankey diagram looks really exciting and is pretty easy to create with JS. Some basic knowledge of web technologies is always beneficial in interactive data visualization. But in reality, everything is uncomplicated and you will understand it all even if you are a beginner.

The process of creating a JavaScript-based Sankey diagram can be split into four steps:

1. Create an HTML page.
2. Add scripts.
3. Set data.
4. Write some JS code.

Let’s go through them together.

### 1. Create an HTML page
To start with, create a basic HTML page to hold the intended Sankey chart and define a block element in it.

To reference this `<div>` later in the code, give it an identification attribute (“container” in this example) and set the desired style properties (here, the width and height are 100%, which will let the diagram stretch across the entire web page).

```html
<html>
  <head>
    <title>JavaScript Sankey Diagram</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. Add scripts

The next step is to add the necessary scripts.

In this tutorial, I am using the [AnyChart JavaScript library](https://www.anychart.com). It is flexible and easy to use thanks to its comprehensive [documentation](https://docs.anychart.com) along with many readymade [chart examples](https://www.anychart.com/products/anychart/gallery/).

AnyChart is modular, which lets you minimize the size of the JavaScript code running on your web page by connecting the chart types and features you actually need and nothing more. For the Sankey chart development, you just need the [core module](https://docs.anychart.com/Quick_Start/Modules#core) along with the specific [Sankey module](https://docs.anychart.com/Quick_Start/Modules#sankey_diagram). Add both to the `<head>` section of the HTML page.

```html
<html>
  <head>
    <title>JavaScript Sankey Diagram</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-sankey.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>
      // All the code for the JS Sankey Diagram will come here.
    </script>
  </body>
</html>
```

### 3. Set data

Data for this tutorial is taken from the [Titanic dataset on Kaggle](https://www.kaggle.com/datasets/ibrahimelsayed182/titanic-dataset). I have only put it in a form [suitable](https://docs.anychart.com/Basic_Charts/Sankey_Diagram#data) for a Sankey diagram.

The dataset is not large, so you can directly add it to the code just like that. (For a particular task, you may opt for another way of [working with data](https://docs.anychart.com/Working_with_Data/Overview), of course.)

```javascript
const data = [
  {from: 'First Class', to: 'Child', value: 6},
  {from: 'Second Class', to: 'Child', value: 24},
  {from: 'Third Class', to: 'Child', value: 79},
  {from: 'Crew', to: 'Child', value: 0},
  {from: 'First Class', to: 'Adult', value: 319},
  {from: 'Second Class', to: 'Adult', value: 261},
  {from: 'Third Class', to: 'Adult', value: 627},
  {from: 'Crew', to: 'Adult', value: 885},
  {from: 'Child', to: 'Female', value: 45},
  {from: 'Child', to: 'Male', value: 64},
  {from: 'Adult', to: 'Female', value: 425},
  {from: 'Adult', to: 'Male', value: 1667},
  {from: 'Female', to: 'Survived', value: 344},
  {from: 'Female', to: 'Perished', value: 126},
  {from: 'Male', to: 'Survived', value: 367},
  {from: 'Male', to: 'Perished', value: 1364},
]
```

That’s it, everybody is on board, and now it’s time to set sail by writing a few lines of JS charting code!

### 4. Write some JS code

It may feel overwhelming to write code if you do not have much experience doing that. But for an elegant Sankey diagram, some very simple basic code is more than enough.

Before anything else, add the `anychart.onDocumentReady()` function enclosing all the code, which ensures that everything in it will only run once the page is ready. The first thing to add inside is the data.

```javascript
anychart.onDocumentReady(function () {

  // add data
  const data = [
    {from: 'First Class', to: 'Child', value: 6},
    {from: 'Second Class', to: 'Child', value: 24},
    {from: 'Third Class', to: 'Child', value: 79},
    {from: 'Crew', to: 'Child', value: 0},
    {from: 'First Class', to: 'Adult', value: 319},
    {from: 'Second Class', to: 'Adult', value: 261},
    {from: 'Third Class', to: 'Adult', value: 627},
    {from: 'Crew', to: 'Adult', value: 885},
    {from: 'Child', to: 'Female', value: 45},
    {from: 'Child', to: 'Male', value: 64},
    {from: 'Adult', to: 'Female', value: 425},
    {from: 'Adult', to: 'Male', value: 1667},
    {from: 'Female', to: 'Survived', value: 344},
    {from: 'Female', to: 'Perished', value: 126},
    {from: 'Male', to: 'Survived', value: 367},
    {from: 'Male', to: 'Perished', value: 1364},
  ]

  // everything else goes here
	
});
```

Now, create a Sankey diagram instance using the built-in charting function and load the data.

```javascript
let chart = anychart.sankey();
chart.data(data);
```

A bit of padding will make sure labels do not get cut off, and a chart title is always helpful.

```javascript
chart.padding(20, 40);  
chart.title('Titanic Survivors');
```

Lastly, just reference the container element to show where the Sankey chart needs to be displayed and draw the resulting visualization.

```javascript
chart.container('container');
chart.draw();
```

Voilà! A fantastic and functional JavaScript-based Sankey diagram is all ready!

![A basic Sankey diagram built with JavaScript](https://www.anychart.com/blog/wp-content/uploads/2022/05/sankey-basic.png)

Take a look at this initial JS Sankey chart on [AnyChart Playground](https://playground.anychart.com/H7EhB3jq/) with the full JS/CSS/HTML code (also provided below for your convenience).

```html
<html>
  <head>
    <title>JavaScript Sankey Diagram</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-sankey.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 () {
  
        // add data
        const data = [
          {from: "First Class", to: "Child", value: 6},
          {from: "Second Class", to: "Child", value: 24},
          {from: "Third Class", to: "Child", value: 79},
          {from: "Crew", to: "Child", value: 0},
          {from: "First Class", to: "Adult", value: 319},
          {from: "Second Class", to: "Adult", value: 261},
          {from: "Third Class", to: "Adult", value: 627},
          {from: "Crew", to: "Adult", value: 885},
          {from: "Child", to: "Female", value: 45},
          {from: "Child", to: "Male", value: 64},
          {from: "Adult", to: "Female", value: 425},
          {from: "Adult", to: "Male", value: 1667},
          {from: "Female", to: "Survived", value: 344},
          {from: "Female", to: "Perished", value: 126},
          {from: "Male", to: "Survived", value: 367},
          {from: "Male", to: "Perished", value: 1364}
        ];
  
        // create a sankey diagram instance
        let chart = anychart.sankey();

        // load the data to the sankey diagram instance
        chart.data(data);

        // set the chart's padding
        chart.padding(20, 40);
  
        // add a title
        chart.title('Titanic Survivors');
  
        // set the chart container id
        chart.container("container");

        // draw the chart
        chart.draw();
  
      });
    </script>
  </body>
</html>
```

## Customizing a JavaScript Sankey Diagram

A huge advantage of using a robust JS charting library is the ease with which the initial data visualization is created and the flexibility for further customizations. Let’s see how you can enhance the Sankey diagram’s capabilities and tweak its appearance with some simple modifications.

1. Color Palette
2. Nodes
3. Links
4. Title

**FOR A WALKTHROUGH OF THESE JS SANKEY DIAGRAM CUSTOMIZATIONS, CONTINUE READING [HERE](https://www.anychart.com/blog/2022/05/25/sankey-diagram-js/).**

**MORE JAVASCRIPT CHARTING TUTORIALS ARE AVAILABLE [HERE](https://www.anychart.com/blog/category/javascript-chart-tutorials/).**