How to create live graphs with ChartJS and Javascript

How to create live graphs with ChartJS and Javascript

The complete tutorial for ChartJS

ยท

7 min read

Introduction

Almost always, a website contains graphs. This can be used to show user analytics and create dashboards for example. With a package like ChartJS, you can create multiple types of graphs with your own custom data. Properties such as graph color, size, legends and axes can be set as well. This blog will teach you the basics of ChartJS and how it can be used to create live graphs. So, without further ado, let's begin.

Using ChartJS

First, we will create an HTML file with boilerplate code pasted. The next step is to link the ChartJS file to this code. Add the following script tag right before your closing body tag:

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js" integrity="sha512-sW/w8s4RWTdFFSduOTGtk4isV1+190E/GghVffMA9XczdJ2MDzSzLEubKAs5h0wzgSJOQTRYyaz73L3d6RtJSg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Your file should like like this

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ChartJS Tutorial</title>
</head>

<body>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js" integrity="sha512-sW/w8s4RWTdFFSduOTGtk4isV1+190E/GghVffMA9XczdJ2MDzSzLEubKAs5h0wzgSJOQTRYyaz73L3d6RtJSg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</body>

</html>

That is it! We now have access to all functions related to ChartJS.

Line Graphs

First, we must create a canvas with an id that will be referenced in our javascript code

<canvas id="chart" style="max-width: 500px; max-height: 250px;"></canvas>

Now, we will write our javascript code. An important note: the script tag linking the ChartJS file must be placed above the script tag that contains our own javascript code.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ChartJS Tutorial</title>
</head>

<body>
    <canvas id="chart" style="max-width: 500px; max-height: 250px;"></canvas>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js" integrity="sha512-sW/w8s4RWTdFFSduOTGtk4isV1+190E/GghVffMA9XczdJ2MDzSzLEubKAs5h0wzgSJOQTRYyaz73L3d6RtJSg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script>
        new Chart("chart", {

        })
    </script>
</body>

</html>

The first parameter we must pass to the new Chart is the id of the canvas on our html page (that is chart). The second parameter is an object that will contain all the chart properties and data.

For instance, to create a line graph, we can set the type property to line.

Furthermore, we can set the data property to an object. This object will have two main parameters: labels and datasets.

new Chart("chart", {
    type: "line",
    data: {
        labels: [2008, 2012, 2016, 2020, 2024],
        datasets: [{
            data: [19, 29, 46, 1001, 523]
        }]
    }
})

Our page now looks like this

blog_1.png

We can set a line color using the borderColor property

new Chart("chart", {
    type: "line",
    data: {
        labels: [2008, 2012, 2016, 2020, 2024],
        datasets: [{
            borderColor: "blue",
            data: [19, 29, 46, 1001, 523]
        }]
    }
})

The points can have a color as well. Use the backgroundColor property for this

new Chart("chart", {
    type: "line",
    data: {
        labels: [2008, 2012, 2016, 2020, 2024],
        datasets: [{
            borderColor: "blue",
            backgroundColor: "red",
            data: [19, 29, 46, 1001, 523]
        }]
    }
})

blog_2.png

We can replace the text undefined in the legend with our custom label

new Chart("chart", {
    type: "line",
    data: {
        labels: [2008, 2012, 2016, 2020, 2024],
        datasets: [{
            label: "First Line",
            borderColor: "blue",
            backgroundColor: "red",
            data: [19, 29, 46, 1001, 523]
        }]
    }
})

Title and Axes

After the data property, another property called options can be defined. This will contain configurations for the graph. To add a title, use the following code

new Chart("chart", {
    type: "line",
    data: {
        labels: [2008, 2012, 2016, 2020, 2024],
        datasets: [{
            label: "First Line",
            borderColor: "blue",
            backgroundColor: "red",
            data: [19, 29, 46, 1001, 523]
        }]
    },
    options: {
        plugins: {
            title: {
                display: true,
                text: "Heading"
            }
        }
    }
})

We can add axis values using the below code

new Chart("chart", {
    type: "line",
    data: {
        labels: [2008, 2012, 2016, 2020, 2024],
        datasets: [{
            label: "First Line",
            borderColor: "blue",
            backgroundColor: "red",
            data: [19, 29, 46, 1001, 523]
        }]
    },
    options: {
        plugins: {
            title: {
                display: true,
                text: "Heading"
            }
        },
        scales: {
            y: {
                title: {
                    display: true,
                    text: 'Y-Axis'
                }
            },
            x: {
                title: {
                    display: true,
                    text: 'X-Axis'
                }
            }
        }
    }
})

blog_3.png

Creating a live line graph

First, we must have some randomly varying numbers that will act as the live data. So, in our script tag, we will create a function that gets random numbers. Note that this is the tag placed after the link to ChartJS.

<script>
    function getRandom(){
        return Math.floor(Math.random() * 1000); // Returning a random number between 0 and 999
    }
</script>

Next, we will define our data and labels array

<script>
    function getRandom(){
        return Math.floor(Math.random() * 1000); // Returning a random number between 0 and 999
    }

    let data = [];
    let labels = [];
</script>

Now, we will create the line graph using ChartJS. The values of data and labels properties for this graph will correspond to the variables we just created.

Also, we must assign a variable the value of this new chart. It will be used later in the code.

<script>
    function getRandom(){
        return Math.floor(Math.random() * 1000);
    }

    let data = [];
    let labels = [];

    const chart = new Chart("chart", {
        type: "line",
        data: {
            labels: labels, // Labels is the empty array declared above
            datasets: [{
                label: "First Line",
                borderColor: "blue",
                backgroundColor: "red",
                data: data // Data is the empty array declared above
            }]
        }
    })
</script>

A function defined inside setInterval runs every n milliseconds where n is the number defined in the second parameter. Using it, we can add new elements to our labels and data array.

Say we want to change our graph every second. We can pass 1000ms as the second parameter in setInterval. Now as the first parameter, we will pass the function we want to run every second

setInterval(() => {
    // function goes here
}, 1000)

In this function, we would like to increase our labels array by one element. So, after 5 seconds, it looks like [0, 1, 2, 3, 4]. After 10 seconds, it looks like [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]. This can be done like so

setInterval(() => {
    if (labels.length > 0){
        labels.push(labels[labels.length - 1] + 1);
    } else{
        labels.push(0);
    }
}, 1000)

In the above code, if the labels array is empty, it will add zero. Else, it will add the next number.

Now, let us manipulate the data array to add a new random number every second

setInterval(() => {
    if (labels.length > 0){
        labels.push(labels[labels.length - 1] + 1);
    } else{
        labels.push(0);
    }

    const random = getRandom();
    data.push(random);
}, 1000)

So, our data now changes every second as well

However, if look at our graph, it has not changed yet. This is because even though are data is changing, this change is not being reflected on the graph. We need to update the graph after our data is updated.

To do this, we will use the .update function upon the chart variable whose value is our ChartJS chart

setInterval(() => {
    if (labels.length > 0){
        labels.push(labels[labels.length - 1] + 1);
    } else{
        labels.push(0);
    }

    const random = getRandom();
    data.push(random);

    chart.update();
}, 1000)

With this, our graph changes every second.

All the code

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ChartJS Tutorial</title>
</head>

<body>
    <div style="width: 500px; height: 250px; margin: auto;">
        <canvas id="chart" style="width: 100%; height: 100%;"></canvas>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js" integrity="sha512-sW/w8s4RWTdFFSduOTGtk4isV1+190E/GghVffMA9XczdJ2MDzSzLEubKAs5h0wzgSJOQTRYyaz73L3d6RtJSg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script>
        function getRandom(){
            return Math.floor(Math.random() * 1000);
        }

        const labels = [];
        const data = [];
        const chart = new Chart("chart", {
            type: "line",
            data: {
                labels: labels, // Labels is the empty array declared above
                datasets: [{
                    label: "First Line",
                    borderColor: "blue",
                    backgroundColor: "red",
                    data: data // Data is the empty array declared above
                }]
            }
        })

        setInterval(() => {
            if (labels.length > 0){
                labels.push(labels[labels.length - 1] + 1);
            } else{
                labels.push(0);
            }
            let random = getRandom();
            data.push(random);
            chart.update();
        }, 1000)

    </script>
</body>

</html>

Conclusion

In the above example, our live data came from the client side javascript. So, our graph changed without the need to refresh. However, if the data you are getting is from a server, the user would need to refresh the page to see new changes. To allow for a smoother user interface, a framework like ReactJS can be used so that when server data changes, it is reflected on the frontend without the need to refresh.

That is it from this blog. Thank you for reading and happy coding !

ย