Tweet about RGraph
Follow for HTML5 news
Bookmark and share:

# RGraph: HTML5 canvas graph library - Updating your graphs dynamically

The example on the right shows a line chart that automatically updates itself every 250 milliseconds. An ideal use for this could be showing a networks bandwidth usage, or a servers load value.

This particular example shows a stacked line chart with two data series, though if you're showing load/stress values, a non-filled chart might be a better choice.

To get up-to-date data from your server you could simply have the page refresh itself, storing the data on the server, or use AJAX if you want the data stored client-side.

Be careful of the data types you use to pass the data to RGraph - you should use numbers to represent values, not strings.

    <canvas id="cvs" width="600" height="250">[No canvas support]</canvas>

    <script>
        d1 = [];
        d2 = [];

        // Pre-pad the arrays with 100 null values
        for (var i=0; i< 100; ++i) {
            d1.push(null);
            d2.push(null);
        }

        function getGraph(id, d1, d2)
        {
            var graph = new RGraph.Line(id, d1, d2);
            graph.Set('chart.gutter', 25);
            graph.Set('chart.background.barcolor1', 'white');
            graph.Set('chart.background.barcolor2', 'white');
            graph.Set('chart.title.xaxis', 'Time');
            graph.Set('chart.filled', true);
            graph.Set('chart.fillstyle', ['#daf1fa', '#faa']);
            graph.Set('chart.colors', ['rgb(169, 222, 244)', 'red']);
            graph.Set('chart.linewidth', 3);
            graph.Set('chart.ymax', 20);
            graph.Set('chart.xticks', 25);

            return graph;
        }

        function drawGraph (e)
        {
            // Clear the canvas and redraw the graph
            RGraph.Clear(document.getElementById("cvs"));
            var graph = getGraph('cvs', d1, d2);
            graph.Draw();

            // Add some data to the data arrays
            d1.push(RGraph.random(5, 10));
            d2.push(RGraph.random(5, 10));

            // Get rid of the first values of the arrays
            if (d1.length > 100) {
                d1 = RGraph.array_shift(d1);
                d2 = RGraph.array_shift(d2);
            }

            setTimeout(drawGraph,250);
        }

        drawGraph();
    </script>