Implement Advanced Chart Types like Heatmaps and Contour Plots
Tags: javascript, lowcode, tooljet, tutorial
Published: 2024-05-14 12:53:58

## Introduction

This tutorial will explore implementing advanced chart types like Heatmaps and Contour plots using ToolJet’s Chart Component. [ToolJet](https://github.com/ToolJet/ToolJet) provides excellent tools for visualizing complex datasets. By the end of this tutorial, you will learn how to integrate these sophisticated visualizations into your applications. Heatmaps and contour plots are invaluable for revealing patterns and gradients in data. Let's dive into the steps to create these visual elements efficiently.

### Prerequisites:

- **ToolJet (https://github.com/ToolJet/ToolJet) :** An open-source, low-code platform for quickly building and deploying internal tools. Sign up for a free ToolJet cloud account [here](https://app.tooljet.com/).
- **Basic understanding of JavaScript :** Familiarity with JavaScript concepts will help you follow the tutorial more effectively.

Here’s what our final application will look like:

![Final Application](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nz5snuexm4kyncfv17yh.png)

For this tutorial, we will use temperature variations during different times of the day across the week for London and Paris.

The weather data will be stored in two tables in the **[ToolJet Database](https://docs.tooljet.com/docs/tooljet-db/tooljet-database)**.

![London Weather DB](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8vqqladt6xgmoi8muc1x.png)

![Paris Weather DB](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4pi9f13ku329ewq6argz.png)

## Designing the UI

Creating a user-friendly UI is pretty straightforward with the help of ToolJet’s built-in components.

Let’s start by creating the header.

### 1. Adding the Header 

- Drag and drop the **Text** Component from the components library on the canvas.
- Rename the Text Component to _headerText_, and change the Data property to **London and Paris Weather Analysis**.
- In the **Styles** section, change the font size to 28 and the font weight to bold.

![Header](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tn7ko43wt3vostaxxdct.png)

### 2. Adding the Chart Component

Since we will analyse the data through **Charts**, we will use ToolJet’s Chart Component.

- Drag and drop a Chart component from the Components library. 
- Select the Chart component, rename it to _heatmapChart_ and enable **Plotly JSON Chart Schema**, and in the **JSON Description** section.
- Add the following code for a placeholder chart:

```
{
    "data": [
        {
            "z": [[1, 20, 30], [20, 1, 60], [30, 60, 1]],
            "x": ["Experiment 1", "Experiment 2", "Experiment 3"],
            "y": ["Trial 1", "Trial 2", "Trial 3"],
            "type": "heatmap"
        }
    ]
}
```

- This will create a placeholder heatmap based on the data provided above. In the later sections of the tutorial, we will be able to create a heatmap based on our own data. 

![Initial Heatmap](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4clzlb7l1nlv5qvoosiy.png)

- Next, drag and drop another Chart component next to the heatmap. Since this will be a contour, rename it to _countourChart_.
- Enable the **Plotly JSON Chart Schema** and provide the following **JSON Description**:

```
{
"data": [
    {
      "x": [1, 2, 3, 4],
      "y": [1, 2, 3, 4],
      "z": [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7]],
      "type": "contour"
    }
  ]
}
```

- You should now see a contour plot next to the heatmap.

![Contour](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jbdbs4hmfob48kj5irea.png)

_To know more about the examples available for the Chart component, visit ToolJet’s documentation for [Charts](https://docs.tooljet.com/docs/widgets/chart/chart-examples)._

The UI is now ready. It’s time to display some actual data through Heatmaps and Contours.

## Analysing Data through Heatmap and Contour Plot

Let’s fetch London’s temperature variation data from our _londonWeather DB_ and displaying it through the Heatmap. Here are the steps to implement it.

### 1. Fetching the Data for the Heatmap

- Expand the **Query Panel** at the bottom of the screen and create a new [query](https://docs.tooljet.com/docs/tooljet-concepts/what-are-queries) - rename it to _fetchLondonWeather_.
- Select _londonWeather_ as the **Table name** and **List rows** as the **Operations**.
- To ensure that the query runs every time the application loads, in the **Settings** property toggle, **Run this query on application load?**
- Click the **Run** button to see the data fetched from your _londonWeather_ database.

![Fetch London Weather](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qaepacz691akpxg7io6e.png)

### 2. Creating RunJS Query to Display the Data on the Heatmap

As we can now fetch our data, we must convert it into the format that the heatmap accepts. 

- Expand the Query Panel, create a new **Run JavaScript Code** query, and rename it to _heatmap_.
- In the code editor, paste the following code:

```
//run the fetchLondonWeather query
await queries.fetchLondonWeather.run();
//get data from the fetchLondonWeather query
const data = queries.fetchLondonWeather.getData();

function convertDataToHeatmapJSON(data) {
    // Assuming each object has a time_day label and each weekday as a key
    const days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'];
    const times = data.map(item => item.time);
    const z = data.map(item =>
        days.map(day => item[day]) // Construct rows for each time slot
    );

    // Constructing the Plotly JSON
    const plotlyJSON = {
            x: days.map(day => day.charAt(0).toUpperCase() + day.slice(1)), // Capitalize day names
            y: times,
            z: z,
      type: 'heatmap',
    };

    return plotlyJSON;
}

const heatmapJSON = convertDataToHeatmapJSON(data);

const heatmapData = JSON.stringify(heatmapJSON); //converting the data to string

return heatmapData;
```

_The JavaScript code above converts the data fetched from the londonWeather database to a **Plotly JSON Chart Schema** for a heatmap._

- Click on the **Run** button to see the data formatted to three axes, named **x**, **y** and **z**.
- Next, in the **JSON Description** of the _heatmapChart_ component, replace “**data**” value with `{{queries.heatmap.data}}`.
- If you follow the above steps correctly, you can see the data displayed via heatmap.

![London Heatmap](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qauzh4tg4kykl2l8pomq.png)
_To make the heatmap more descriptive, replace the **Title** from the properties panel with **London**._

We will use similar data for a different city, Paris, to implement a contour plot. As mentioned in the tutorial, our data is stored in the _parisWeather DB_.

### 3. Fetching the Data for the Contour Plot

To fetch the data for Paris, we need to follow the similar steps mentioned in Step 1.

- Expand the Query Panel, create a new **ToolJet Database query**, and rename it to _fetchParisWeather_.
- Select _parisWeather_ as the **Table name** and **List rows** as the **Operations**. Also, toggle the **Run this query on application load?.**
- Click the **Run** button to see the data fetched from your _parisWeather_ database.

![Fetch Paris Weather](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r4pahw9dda27z0uo9ynf.png)

### 4. Creating RunJS Query to Display the Data on the Contour Plot

Now that we can fetch our data, we must convert it into the format the contour plot accepts.

- Expand the Query Panel, create a new **Run JavaScript Code** query, and rename it to _contour_.
- In the code editor, paste the following code:

```
//run the fetchParisWeather query
await queries.fetchParisWeather.run();
//get data from the fetchDataParis query
const data = queries.fetchParisWeather.getData();

function convertToContourPlotJSON(data) {
    // Extract unique days and times assuming data is sorted by time
    const days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
    const times = data.map(item => item.time);

    // Construct the z matrix
    const z = data.map(item =>
        days.map(day => item[day.toLowerCase()]) // Access day values; ensure day keys are in lowercase
    );

    // Constructing the Plotly JSON for a contour plot
    const plotlyJSON = {
            x: days,   // Day labels
            y: times,  // Time labels
            z: z,     // Matrix of values
            type: 'contour',
    };

    return plotlyJSON;
}

const contourPlotJSON = convertToContourPlotJSON(data);

const contourData = JSON.stringify(contourPlotJSON); //converting the data to string

return contourData;
```
_The JavaScript code above converts the data fetched from the parisWeather table to a **Plotly JSON Chart Schema** for a contour plot._

- Click on the **Run** button to see the data.
- Next, in the **JSON Description** of the _contourChart_ component, replace “**data**” value with `{{queries.contour.data}}`.
- Following the above steps correctly, you can see the data displayed via a contour plot.

![Paris Contour](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ug72lurcu2cwr1tn0ae6.png)

_Let’s update the **Title** of the contourChart Component to **Paris**._

## Congratulations!

Awesome job completing this tutorial on Implementing Advanced Chart Types like Heatmaps and Contour Plots. This tutorial gives us an overview of using different chart types available on ToolJet to analyse data. To continue exploring other Chart options available on ToolJet, check out the [ToolJet docs](https://docs.tooljet.com/docs/) on charts.