graph on ipad

Overview

This post will walk through how to visualize dynamically updating time series data that is stored in InfluxDB (a time series database), using the JavaScript graphing library: Dygraphs. If you have a preference for a specific visualization library, check out these other graphical integration posts using various libraries—plotly.js, Rickshaw, Highcharts, or you can always build out a dashboard in our very own Chronograf, which is designed exclusively for InfluxDB.

Prep and Setup

To begin with, we’ll need some sample data to display on screen. For this example, I’ll be using the data generated from a separate tutorial written by DevRel Anais Dotis-Georgiou on using the Telegraf exec or tail plugins to collect Bitcoin price and volume data and see it trend over time. I’ll then query for the data in InfluxDB periodically using the HTTP API on the frontend. Let’s get started!

Depending on whether you want to pull in Dygraphs as a script file into your index.html file or import the npm module, you can find all the relevant instructions here. I added several script tags into my index.html file for ease of reference in this case:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Dygraphs Sample</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dygraph/2.1.0/dygraph.min.css" />
    <link rel="stylesheet" type="text/css" href="styles.css">
  </head>
  <body>
    <div id="div_g"></div>
  </body>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/dygraph/2.1.0/dygraph.min.js"></script>
  <script type="text/javascript" src="script.js"></script>
</html>

Querying InfluxDB

Ensure your local instance of InfluxDB is running (you can get all the components of the TICK Stack set up locally or spin up the stack the sandbox way) and that Telegraf is collecting Bitcoin stats by running SELECT "price" FROM "exec"."autogen"."price" WHERE time > now() - 12h in your Influx shell (you can access the Influx shell, with the command influx). With time series data, you always want to scope your queries, so rather than running a SELECT * from exec, we are limiting our results here by selecting specifically for price and limiting by time (12 hrs).

You should receive at least one result when running this query, depending on how long your Telegraf instance has been running and collecting stats via one of the plugins from the tutorial. Alternatively, you can navigate to your local Chronograf instance and verify that you’re successfully collecting data via the Data Explorer page, which has an automatic query builder.

Fetching the Data from InfluxDB

In your script file, you’ll want to fetch the data from InfluxDB using the HTTP API, like so:

const fetchData = () => {
  return fetch(`http://localhost:8086/query?db=exec&q=SELECT%20"price"%20FROM%20"price"`)
    .then( response => {
      if (response.status !== 200) {
        console.log(response);
      }
      return response;
    })
    .then( response => response.json() )
    .then( parsedResponse => {
      const data = [];
      parsedResponse.results[0].series[0].values.map( (elem, i) => {
        let newArr = [];
        newArr.push(new Date(Date.parse(elem[0])));
        newArr.push(elem[1]);
        data.push(newArr);
      });
      return data;
    })
    .catch( error => console.log(error) );
}

Constructing the Graph

We can construct the graph using the Dygraphs constructor function as follows:

const drawGraph = () => {
  let g;
  Promise.resolve(fetchData())
    .then( data => {
      g = new Dygraph(
        document.getElementById("div_g"),
        data,
        {
          drawPoints: true,
          title: 'Bitcoin Pricing',
          titleHeight: 32,
          ylabel: 'Price (USD)',
          xlabel: 'Date',
          strokeWidth: 1.5,
          labels: ['Date', 'Price'],
        });
    });

  window.setInterval( () => {
    console.log(Date.now());
    Promise.resolve(fetchData())
      .then( data => {
        g.updateOptions( { 'file': data } );
      });
  }, 300000);
}

What’s happening in the drawGraph function is that after fetching the data from InfluxDB, we create a new Dygraph, by targeting the element within which to render the graph, add the data array, and add in our options object as the third argument. In order to dynamically update the graph over time, we add a setInterval method to fetch new data every five minutes (unfortunately, any calls more often than that require a paid subscription to the Alpha Vantage API for Bitcoin pricing) and use the updateOptions method to bring in new data.

Summary

If you’ve made it this far, I applaud you. Feel free to check out the source code for a little side-by-side comparison. Additionally, Dygraphs has a gallery of demos available if you want to experiment with a myriad of styles. We want to hear all about your creations! Look for us on Twitter: @mschae16 or @influxDB.

Contact Sales