Programming Real Time Charts & Graphs with JavaScript

Programming Real Time Charts & Graphs with JavaScript Thumbnail
Published on 18. May 2019Last updated on 22. June 2020

Real Time Charts can display data in real time. This means that the data is updated permanently to always display the current chart. To create the Real Time Chart, we use JavaScript and the Google Chart API.

Advertisement

These live diagrams are often used in dashboards to show developments of e.g. temperatures or prices. Diverse areas of application and they really look good. See for yourself!

Real Time Chart – Line Chart

I show you here, which you can create this Real Time Chart. It updates itself every 250 milliseconds and shows (in our example) random data. In productive use it can read and display data from a database or directly from a sensor.

That’s not all. The same concept can be transferred 1:1 to other diagrams, among others:

Google Chart API – Short introduction

The Google Chart API is a free service from Google that allows us to display various charts and graphs on our website or web application.

Advertisement

Additionally, the charts offer interactive functions for the user. For example, a pop-up with the values of the current element can be displayed when hovering.

The data is displayed statically. But we develop our own system around it, so that we can update the data in a certain interval, and thus get our Real Time Chart. The data is then updated (almost) live in real time and the desired effect is achieved.

1. Embed Google Chart API

The Google Chart API must be included via this script tag. A local hosting is not possible here, because Google’s Terms of Service prohibit this.

<script type="text/javascript" loading="lazy" src="https://www.gstatic.com/charts/loader.js"></script>

2. Create HTML Container

Next we need a simple div. there the Google API later draws the chart as SVG or VML.

<div id="chart_div"></div>

3. Initialize and configure Google Chart API

In the following code we load the line chart package from the Google Chart Packages. Then we call the function drawChart() as callback. This will be executed as soon as the API is fully loaded.

Advertisement
// load current chart package
google.charts.load("current", {
  packages: ["corechart", "line"]
});

// set callback function when api loaded
google.charts.setOnLoadCallback(drawChart);

Next we create an object with label (not shown) and default data for the chart. We also need an array with options. Here we set the title and the axes label.

All parameters can be found in detail in the Google Chart documentation.

Then we select our HTML container and let chart.draw(data, options) draw the chart.

function drawChart() {

  // create data object with default value
  let data = google.visualization.arrayToDataTable([
    ["Year", "CPU Usage"],
    [0, 0]
  ]);

  // create options object with titles, colors, etc.
  let options = {
    title: "CPU Usage",
    hAxis: {
      title: "Time"
    },
    vAxis: {
      title: "Usage"
    }
  };

  // draw chart on load
  let chart = new google.visualization.LineChart(
    document.getElementById("chart_div")
  );
  chart.draw(data, options);
}

With the previous code the table is now already drawn and we can get a first look at it.

Simple line chart without data - created with the Google Chart API
Simple line chart without data – created with the Google Chart API

4. Update data dynamically

Now we come to the most important part, why you are here at all – the dynamic updating of the data. This is how we “create” our Real Time Chart.

Advertisement

We insert new data into the chart at intervals of 250ms.

The variable index is used to insert another element as a line and has no further meaning. In this example I generate random numbers, which should be understood as CPU usage. Here you have to insert your own data in line 5.

You can do this for example via an Ajax Request. So you can use PHP and a database class to read data directly from your database or you can write your own RestAPI, e.g. with Node.js.

let index = 0;
setInterval(function() {

  // instead of this random, you can make an ajax call for the current cpu usage or what ever data you want to display
  let random = Math.random() * 30 + 20;

  data.addRow([index, random]);
  chart.draw(data, options);

  index++;
}, 250);

Here now again the complete code in one file. For clarity I have packed everything into one file. But you should put JavaScript and CSS in extra files.

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

<head>
    <meta charset="UTF-8" />
    <title>Document</title>
    <style>
        #chart_div {
            width: 1200px;
        }
        
        body {
            display: flex;
            justify-content: center;
            align-items: center;
        }
    </style>
</head>

<body>
    <!-- CONTAINER FOR CHART -->
    <div id="chart_div"></div>
    <script type="text/javascript" loading="lazy" src="https://www.gstatic.com/charts/loader.js"></script>
    <script>

        // load current chart package
        google.charts.load("current", {
            packages: ["corechart", "line"]
        });

        // set callback function when api loaded
        google.charts.setOnLoadCallback(drawChart);

        function drawChart() {

            // create data object with default value
            let data = google.visualization.arrayToDataTable([
                ["Year", "CPU Usage"],
                [0, 0]
            ]);

            // create options object with titles, colors, etc.
            let options = {
                title: "CPU Usage",
                hAxis: {
                    title: "Time"
                },
                vAxis: {
                    title: "Usage"
                }
            };

            // draw chart on load
            let chart = new google.visualization.LineChart(
                document.getElementById("chart_div")
            );
            chart.draw(data, options);

            // interval for adding new data every 250ms
            let index = 0;
            setInterval(function() {

                // instead of this random, you can make an ajax call for the current cpu usage or what ever data you want to display
                let random = Math.random() * 30 + 20;

                data.addRow([index, random]);
                chart.draw(data, options);

                index++;
            }, 250);

        }
    </script>
</body>

</html>

Conclusion

Ready! In this example we have a line chart as a real time chart, but the code works the same way with the other chart types. You often only need to adjust the options and the data structure.

Related Posts
NEW 🚀
NEW 🚀
NEW 🚀
Join the Conversation

2 Comments

Your email address will not be published. Required fields are marked *