How to build charts with Chart.js
Tags: javascript, datavisualization, chartjs
Published: 2023-06-02 07:59:01

---
title: How to build charts with Chart.js
published: true
date: 2023-04-22 01:40:26 UTC
tags: #javascript #datavisualization #chartjs
canonical_url: https://gidakinsanmi.hashnode.dev/how-to-build-charts-with-chartjs
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aqzyaazkrxe019gioyvc.png
---

Chart.js is one of the most popular JavaScript charting libraries. Its the only chart library with over 2.7m weekly downloads on [npm](https://npmjs.com/package/chart.js) and 60k stars on [GitHub](https://github.com/chartjs). With Chart.js, you can easily create and customize different kinds of charts.

At the end of this tutorial, youd be able to install and set up Chart.js, build simple and complex charts and apply customization to your charts.

## Setting up

First, you need to create a folder and create an index.html page within it.

Within index.html, add the following code:

```html
<DOCTYPE html>
<html>
    <head>
        <!-- 01 --> 
        <script></script>
    </head>
    <body>
        <!-- 02 --> 
        <div style='position: relative;width: 80vw;height: 50vh;'>
            <canvas id=myChart></canvas>
        </div>
        <!-- 03 --> 
        <script>
        </script>
    </body>
</html>

```

Now let's break down the code:

```html
...
<!-- 01 --> 
<script></script>
...

```

This script element will store the address of the Chart.js source files that will be used to create your charts.

```html
...
<!-- 02 --> 
<div style='position:relative;width: 80vw;height: 50vh;'>
    <canvas id=myChart ></canvas>
</div>
...

```

This div element acts as a container for the canvas element. It'll help make your charts responsive. The canvas element will be used by Chart.js for rendering the charts.

```html
...
<!-- 03 --> 
<script>
</script>
...

```

This script element will store the code youll use to create your chart.

## Installing chart.js

Chart.js can be added to your project through any of these methods: npm, CDNJS, jsDelivr and GitHub.

To use [npm](https://npmjs.com/package/chart.js), open your command line interface, navigate to your project's directory and run this command:

```javascript
npm install chart.js

```

Once the package has been successfully installed, store the address of the chart.js file in your script tag.

```javascript
...
<!-- 01 --> 
<script src='path/to/chart.js/dist/chart.umd.js'></script>
...

```

To use [jsDelivr](https://www.jsdelivr.com/), click on [https://www.jsdelivr.com/package/npm/chart.js?path=dist](https://www.jsdelivr.com/package/npm/chart.js?path=dist), copy one of the addresses of Chart.js and store the copied address in your script tag.

```javascript
...
<!-- 01 --> 
<script src='https://cdn.jsdelivr.net/npm/chart.js@4.2.1/dist/chart.umd.min.js'></script>
...

```

To use [CDNJS](https://cdnjs.com/), click on [https://cdnjs.com/libraries/Chart.js](https://cdnjs.com/libraries/Chart.js), copy one of the chart.umd.js links and store the copied link in your script tag.

```javascript
...
<!-- 01 --> 
<script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.2.1/chart.umd.js'></script>
...

```

To use [GitHub](https://github.com/chartjs/Chart.js/releases/latest), first download or clone the chart.js Github repository on your system. Then [build](https://www.chartjs.org/docs/latest/developers/contributing.html#building-and-testing) it to generate the dist files. finally, store the address in your script tag.

## Creating charts

### How to create a single bar chart

A bar/column chart is a chart that represents values in form of rectangular bars with lengths proportional to the values they represent.

To create a bar chart, add the following code within your script element:

```javascript

<!-- 04 -->
<script>
    // 001 
    Let ctx = document.getElementById('myChart');
    // 002 
    new Chart(ctx, {
        // 003 
        type: 'bar',
        // 004
        data: {
            // 005
            labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
            // 006
            datasets: [{
                // 007
                label: 'Bread produced (in thousands)',
                // 008
                data: [10, 50, 40, 90, 55],
                // 009
                borderWidth: 1
            }]
        },
        // 010
        options: {
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
</script>

```

Result:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1682102239093/df299219-4a5b-4262-9c76-75134e220f55.png)

Now let's break down the code:

```javascript
...
// 001 
Let ctx = document.getElementById('myChart');
...

```

We used the [getElementById()](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById) method to select the canvas element and stored it in a variable.

```javascript
...
// 002
new Chart(ctx, {...})
...

```

We created an instance of the Chart object with 2 arguments. The first argument references the canvas element your chart will be rendered in while the second contains the data and configurations for your bar chart.

```javascript
...
// 003 
type: 'bar',
...

```

When the type property's value is 'bar', it means you want to create a bar chart.

```javascript
...
// 004
data: {
    ...
}
...

```

The data property contains the data and configuration for your bar chart datasets.

```javascript
...
// 005
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
...

```

The labels property is used for labelling the x-axis of the bar chart.

```javascript
...
// 006
datasets: [...],
...

```

The datasets property stores the data, labels and configurations of your datasets.

```javascript
...
// 007
label: 'Bread produced (in thousands)',
...

```

The label property stores the labels of the datasets.

```
...
// 008
data: [10, 50, 40, 90, 55],
...

```

The data property stores the values of your datasets.

```javascript
...
// 009
borderWidth: 1
...

```

The borderWidth property is used to customize the bar chart's border width. Navigate to ' **customizing your chart**' to check more customization properties.

```javascript
...
// 010
options: {...}
...

```

The options property contains configuration for the scales, axis and overall styling for the bar chart

### How to create a horizontal bar chart

To make it a horizontal bar chart, change the bar chart indexAxis property to y

```javascript
...
// 010
options: {
    indexAxis: 'y',
    scales: {
        y: {
            beginAtZero: true
        }
    }
}
...

```

Result:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1682102679456/1a2c2a01-3cc9-4faf-b439-5219064a8ff8.png)

### How to create a clustered bar chart

To create a clustered bar chart, add more elements to your datasets property.

```javascript
...
// 006
datasets: [
    {
        label: 'Bread produced (thousands)',
        data: [10, 20, 40, 90, 55],
        borderWidth: 1
    }, {
        label: 'Drinks produced (thousands)',
        data: [50, 70, 20, 60, 40],
        borderWidth: 1
    }
]
...

```

Result:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1682103373082/bce8ac83-b97b-4f78-b93b-aceffb56a941.png)

### How to create a stacked bar chart

To create a stacked bar chart, add more than one element to your datasets property and change the stacked property of x and y axis to true.

```javascript
...
// 010
options: {
    scales: {
        x: {
            stacked: true
        }.
        y: {
            stacked: true,
            beginAtZero: true
        }
    }
}
...

```

Result:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1682109313970/11ea650c-52b5-4c6c-8774-b520b3757feb.png)

### How to create a pie and doughnut chart

A pie and doughnut chart displays data in form of a circle divided into segments with each segment representing a category.

To create a doughnut chart, add the following code:

```javascript

<!04 ->
<script>
    // 001 
    Let ctx = document.getElementById('myChart');
    // 002 
    New Chart(ctx, {
        // 003 
        type: "doughnut",
        // 004
        data: {
            // 005
            labels: ['Bread', 'Drink', 'Software'],
            // 006
            datasets: [{
                // 007
                label: 'Sales by product (thousands)',
                // 008
                data: [90, 140, 250],
                // 009
                backgroundColor: ['red', 'yellow', 'green']
            }]
        }
    });
</script>

```

Result:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1682104241189/c6e84015-5bc6-48c0-8ede-761ecb719c4b.png)

Here the value of the type property is `'doughnut'`.

To create a pie chart, add the following code:

```javascript

<!04 ->
<script>
    // 001 
    Let ctx = document.getElementById('myChart');
    // 002 
    new Chart(ctx, {
        // 003 
        type: "pie",
        // 004
        data: {
            // 005
            labels: ['Bread', 'Drink', 'Software'],
            // 006
            datasets: [{
                // 007
                label: 'Sales by product (thousands)',
                // 008
                data: [90, 140, 250],
                // 009
                backgroundColor: ['red', 'yellow', 'green']
            }]
        }
    });
</script>

```

Result:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1682104423047/5d150b08-fb61-4124-b57b-bbd9862daca9.png)

Here the value of the type property is `'pie'`.

### How to create a line chart

A line chart is a graphical depiction that represents values in the form of a series of data points connected by lines.

To create a line chart, add the following code:

```javascript

<!04 ->
<script>
    // 001 
    Let ctx = document.getElementById('myChart');
    // 002 
    New Chart(ctx, {
        // 003 
        type: "line",
        // 004
        data: {
            // 005
            labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
            // 006
            datasets: [{
                // 007
                label: 'Sales (thousands)',
                // 008
                data: [100, 90, 130, 220, 145],
                // 009
                borderColor: 'red',
                tension: 0.1
            }]
        }
    });
</script>

```

Result:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1682104678788/721cc964-945c-4b10-95e8-aa011f5da999.png)

Let's break down some of the code.

Here the value of the type property is `'line'`.

The `borderColor` and `tension` properties are some of the customizations for line charts.

### How to create a mixed chart

A mixed chart combines 2 or more different charts.

To create a mixed chart, add the following code:

```javascript

<!04 ->
<script>
    // 001 
    Let ctx = document.getElementById(myChart);
    // 002 
    New Chart(ctx, {
        data: {
            datasets: [
                {
                        type: 'bar',
                        label: 'Drinks produced',
                        data: [30, 10, 15],
                        order: 2
                }, {
                        type: 'line',
                        label: 'Biscuits produced',
                        data: [50, 20, 9],
                        order: 1,
                        tension: 0.5
                }
            ],
            labels: ['Monday', 'Tuesday', 'Wednesday']
        },
        options: {
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
</script>

```

Result:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1682105035197/1c074124-28ca-4258-8bbb-a03f6567f13b.png)

Now let's explain some of the code.

Here we moved the `type` property to the datasets property.

The `order` property describes the stacking order of your charts. the chart with a lower value will be drawn on top while the chart with a higher value will be drawn below.

## Customizing your charts

Some of the most properties that can be added to chart.js charts include:

**1) backgroundColor**: This property specifies a background color for your charts. its value can be solid(`red,blue,..`), RGB/RGBA, HSL/HSLA and HEX(`#FFAA00`). it can be applied to all kinds of charts.

```javascript
...
    datasets: [{
        ...
        backgroundColor: 'rgb(244,004,103)'    
    }],
...

```

Result:

**2) barThickness**: This value specifies the width of a bar chart's bar. if the value is a number, it specifies the width of each bar in pixels.

```javascript

<script>

    Let ctx = document.getElementById(myChart);

    New Chart(ctx, {

        type: bar,

        data: {
            ...
            datasets: [{
                ...
                // 009
                barThickness: 8,

            }],
            ...
    });
</script>

```

**3) borderColor**: This property specifies the border color of your charts. its value can be solid(`red,blue,..`), RGB/RGBA, HSL/HSLA and HEX(`#FFAA00`). it can be applied to all charts.

```javascript
...
    datasets: [{
        ...
        borderColor: 'rgb(244,004,103)'    
    }],
...

```

**4) spacing**: This property specifies the arc offset in pixels. it can only be applied to pie and doughnut charts.

```javascript

<script>

    Let ctx = document.getElementById('myChart');

    New Chart(ctx, {

        type: 'pie',

        data: {
            ...
            datasets: [{
                ...
                // 009
                spacing: 2,

            }],
            ...
    });
</script>

```

**5) tension**: This property specifies the bezier curve tension of your line chart. 0 means it'll be in straight lines.

```javascript

<script>

    Let ctx = document.getElementById('myChart');

    new Chart(ctx, {

        type: 'line',

        data: {
            ...
            datasets: [{
                ...
                // 009
                tension: 0,

            }],
            ...
    });
</script>

```

**6) borderWidth**: This property specified the border width of your charts. its value must be in numbers. it can be applied to all charts.

```javascript
...
    datasets: [{
        ...
        borderWidth: 7    
    }],
...

```

**7) hoverBackgroundColor**: This property specifies the chart's background when hovered. it can be applied to all charts.

```
...
    datasets: [{
        ...
        hoverBackgroundColor: 'red'    
    }],
...

```

**8) hoverBorderColor**: This property specifies the chart's border color when it's being hovered. it can be applied to all charts.

```
...
    datasets: [{
        ...
        hoverBorderColor: 'rgb(244,004,103)'    
    }],
...

```

**9) hoverBorderWidth**: This property specifies the chart's border width when it's being hovered. it can be applied to all charts.

```javascript
...
    datasets: [{
        ...
        hoverBorderWidth: 9    
    }],
...

```

## Responsive charts

In addition to styling your canvas container, there are a few properties that can modify the responsive behaviour of your charts.

**1) responsive**: it specifies whether the chart canvas should be automatically resized when its container size is changed. its default value is true.

```javascript
...
option: {
    ...
    responsive: true
}
...

```

**2) maintainAspectRatio**: it specifies whether the chart's original aspect ratio should be maintained. its default value is true.

```javascript
...
option: {
    ...
    maintainAspectRatio: true
}
...

```

**3) aspectRatio**: it specifies the chart's aspect ratio. its default value can be either 1 or 2 depending on the chart type.

```javascript
...
option: {
    ...
    aspectRatio: 3
}
...

```

## Conclusion

Now you see why chart.js is one of the most popular JavaScript charting libraries. It simplifies how you create charts. if you've reached this far, I need you to give yourself a round of applause. it was easy, right? With the knowledge gained from this article, I'm sure you'd be much more confident in creating charts. Check the [Chart.js documentation](https://www.chartjs.org/docs/latest/getting-started/) if you want to learn about the kinds of charts, plugins and customizations that can be created with Chart.js.

If you enjoyed reading this article, kindly like and share this article across all your social platforms. You can also follow this blog and sign up for my weekly newsletter. Cheers.