Programming JavaScript Dynamic (Live) Chart

Programming JavaScript Dynamic (Live) Chart

Dynamic or Real-Time Charts in JavaScript is a nice feature for your statistics. You can update data without having to reload the page. With the Google Chart API this is quite easy but still very individual. Here I show you the most important functions for your website!

Introduction Google Chart API

The Google Chart API is a free interface from Google that allows us to display various charts and graphs in our website or web application. In addition, the charts offer interactive functions for the user. For example, when hovering, a pop-up with the values of the current element can be displayed. In this tutorial I show basic functions for a dynamic chart. A detailed and (in my opinion) extremely good documentation can be found here.

Here you can find a complete list of all possible charts.

Dynamic Line Chart

Dynamic Line Chart

We will create the following chart in this tutorial. In an interval of 250ms we want to output the CPU usage and display it in our chart.

1. Embed Google Chart API

The Google Chart API must be integrated using this script tag. Local hosting is not possible because Google’s Terms of Service prohibit it. See Google’s FAQ.

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

2. Creating HTML Container

Next, we need a simple div where the Google API will later draw 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 LineChart 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.

// 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 displayed) and default data for the chart. We also need an array of options. Here you can set the title and the axis label. All parameters can be found in detail in the Google Chart documentation.

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

function drawChart() {

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

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

  // draw chart on load
  var 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 take a first look at it.

Google Chart mit Default Werten

4. Loading Data Dynamically

The most interesting part follows now. We insert new data into the chart in an interval of 250ms. The variable index serves 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 e.g. with an Ajax request. A PHP script can provide you with server data or read current numbers from a MySQL database. Alternatively you can call a RestAPI to use other services.

var 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
  var random = Math.random() * 30 + 20;

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

  index++;
}, 250);

Here again the complete code in one file. For clarity I have packed everything into one file. But you should store 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
            var data = google.visualization.arrayToDataTable([
                ["Year", "CPU Usage"],
                [0, 0]
            ]);

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

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

            // interval for adding new data every 250ms
            var 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
                var random = Math.random() * 30 + 20;

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

                index++;
            }, 250);

        }
    </script>
</body>

</html>

Ready! In this example we have a LineChart, but the code works the same with the other Google Charts. All you have to do is adjust the options and the data structure. If you have any questions I will be happy to help you with the comments! 🙂

NEW 🚀
NEW 🚀
NEW 🚀

Leave a comment

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