DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Data Engineering
  3. Data
  4. Visualizing Time Series Data With Dygraphs

Visualizing Time Series Data With Dygraphs

How to visualize dynamically updating time series data that is stored in InfluxDB (a time series database), using the JavaScript graphing library: Dygraphs

Margo Schaedel user avatar by
Margo Schaedel
·
Oct. 05, 18 · Tutorial
Like (3)
Save
Tweet
Share
6.52K Views

Join the DZone community and get the full member experience.

Join For Free

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 front-end. 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.

Data (computing) Time series

Published at DZone with permission of Margo Schaedel, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Apache Kafka vs. Memphis.dev
  • Memory Debugging: A Deep Level of Insight
  • Why It Is Important To Have an Ownership as a DevOps Engineer
  • When AI Strengthens Good Old Chatbots: A Brief History of Conversational AI

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: