Dygraphs Blog


Group Information

Exposition Assignment

Group Number: J-023

Topic: Dygraphs

One-line description: Fast, flexible open-source JavaScript charting library for large datasets.


Introduction

Dygraphs is an open-source Javascript charting library that is designed for interactive visualization of large time-series datasets. It enables real-time data analysis, allowing users to hover over graphs to view precise data points. Dygraphs supports multiple data series, making it useful for comparing trends over time. It supports real-time updates, zooming and panning. Additionally, it supports CSV and JSON formats, making it easy to integrate with various data sources.


Installation and Setup

Dygraphs is easy to use and requires minimal setup.

Including Dygraphs In Your Project

There are multiple ways to include Dygraphs in your project.

Using a Content Delivery Network (CDN)

A content delivery network (CDN) is a network of distributed servers that deliver web content (e.g., JavaScript, CSS etc.) from the closest servers to users, improving load speed and performance. CDNs help handle high traffic efficiently. UNPKG is a CDN that hosts dygraphs.

<script type = "text/javascript" src = "https://unpkg.com/dygraphs@2.2.1/dist/dygraph.min.js"></script>
<link rel = "stylesheet" type = "text/css" href = "https://unpkg.com/dygraphs@2.2.1/dist/dygraph.min.css" />

Include this code inside the <head> section of an HTML page to use Dygraphs.

Installing via npm

If you are using a JavaScript framework, install Dygraphs using npm.

npm install dygraphs

Then, import it into your JavaScript file.

import Dygraph from "dygraphs";

Verifying Installation

In order to confirm whether Dygraphs has been loaded successfully or not, run the following command:

console.log(typeof Dygraph); 
// Expected output: "function"

If you are using an HTML file, include this as part of the <script> section of the <body> section. If you are using a Javascript file, add this command to the file containing the import.

Once you have included Dygraphs into your project, you can use it directly.


Key Features and Code Examples

Basic Line Chart

It is simple to create an interactive line chart with minimal code. Below is an example:

<!-- Creating div, specifying width and height and ensuring it is centered -->
<div id = "graph1" style = "width: 100%; height: 400px; margin: auto; display: block;"></div>

<script>
  document.addEventListener("DOMContentLoaded", function() {
    // Defining data to graph
    var data = "Date,Value\n" +
               "2025-02-01,100\n" +
               "2025-02-02,200\n" +
               "2025-02-03,150\n" +
               "2025-02-04,250\n";

    // Creating Dygraph element
    new Dygraph(document.getElementById("graph1"), data, {
      title: 'Basic Line Chart',
      xlabel: 'Date',
      ylabel: 'Value',
      legend: 'always'
    });
  });
</script>

Hovering the mouse over the graph gives the x-value and the y-value.

Zooming and Panning

Dygraphs makes it easy to zoom and pan across the timeline easily.

To zoom, drag across the part of the graph you want to look at closer. To pan, hold shift and drag in the direction you want to move in. To reset the graph, double click. The video below illustrates this.

Adding multiple data series

Dygraphs allows plotting of multiple series on the same graph for easy trend comparisons.

<div id = "graph2" style = "width: 100%; height: 400px; margin: auto; display: block;"></div>

<script>
  document.addEventListener("DOMContentLoaded", function() {
    var data = "Date,Series1,Series2\n" +
               "2025-02-01,100,300\n" +
               "2025-02-02,200,400\n" +
               "2025-02-03,150,600\n" +
               "2025-02-04,250,850\n";
    
    new Dygraph(document.getElementById("graph2"), data, {
      title: 'Multiple Series',
      xlabel: 'Date',
      ylabel: 'Value',
      labels: ['Date', 'Series 1', 'Series 2'],
      colors: ['blue', 'red'],
      legend: 'always'
    });
  });
</script>

Adding Annotations

Dygraphs allows user to highlight key data points using annotations.

<div id = "graph3" style = "width: 100%; height: 400px; margin: auto; display: block;"></div>

<script>
  document.addEventListener("DOMContentLoaded", function() {
    var data = "Date,Temperature\n" +
               "2025-02-01,22\n" +
               "2025-02-02,24\n" +
               "2025-02-03,23\n" +
               "2025-02-04,25\n";

    var graph = new Dygraph(document.getElementById("graph3"), data, {
      title: 'Using Annotations',
      xlabel: 'Date',
      ylabel: 'Temperature (°C)',
      legend: 'always'
    });

    graph.setAnnotations([
      {
        series: "Temperature",
        x: "2025-02-02",
        shortText: "A",
        text: "Annotation",
      }
    ]);
  });
</script>

Handling Large Datasets

Dygraphs is optimized to handle a large number of data points without lag.

<div id = "graph4" style = "width: 100%; height: 400px; margin: auto; display: block;"></div>

<script>
  document.addEventListener("DOMContentLoaded", function() {
    let data = "Date,Value\n";

    for (let i = 0; i < 1000; i++) {
      let date = new Date(2025, 0, i + 1).toISOString().split('T')[0];
      data += `${date},${(Math.random() * 100).toFixed(2)}\n`;
    }

    new Dygraph(document.getElementById("graph4"), data, {
      title: 'Large Dataset',
      xlabel: 'Date',
      ylabel: 'Random Values',
      legend: 'always',
      colors: ['orange'],
    });
  });
</script>

CSV and JSON Support

Dygraphs can load data from CSV strings or JSON files.

To illustrate, we have stored the following data in a CSV and JSON file.

Date Value
2025-02-01 100
2025-02-02 200
2025-02-03 150
2025-02-04 250
2025-02-05 300

Loading CSV

<div id = "graph5" style = "width: 100%; height: 400px; margin: auto; display: block;"></div>

<script>
  document.addEventListener("DOMContentLoaded", function() {
    fetch("https://raw.githubusercontent.com/sd-del/dygraphs/master/data.csv")
      .then(response => response.text())
      .then(csvData => {
        new Dygraph(document.getElementById("graph5"), csvData, {
          title: 'CSV Graph',
          xlabel: 'Date',
          ylabel: 'Value',
          legend: 'always'
        });
      })
      .catch(error => console.error("Error loading CSV:", error));
  });
</script>

Loading JSON

<div id = "graph6" style = "width: 100%; height: 400px; margin: auto; display: block;"></div>

<script>
  document.addEventListener("DOMContentLoaded", function() {
    fetch("https://raw.githubusercontent.com/sd-del/dygraphs/master/data.json")
      .then(response => response.json())
      .then(jsonData => {
        let data = "Date,Value\n"; 
        jsonData.forEach(entry => {
          data += `${entry.Date},${entry.Value}\n`;
        });

        new Dygraph(document.getElementById("graph6"), data, {
          title: 'JSON Graph',
          xlabel: 'Date',
          ylabel: 'Value',
          legend: 'always'
        });
      })
      .catch(error => console.error("Error loading JSON:", error));
  });
</script>

Real-Time Updates

Dygraphs dynamically updates graphs for live data visualization.

<div id = "graph7" style = "width: 100%; height: 400px; margin: auto; display: block;"></div>

<script>
  document.addEventListener("DOMContentLoaded", function() {
    let data = [];
    let startTime = new Date().getTime();
    for (let i = 30; i >= 0; i--) {
      data.push([new Date(startTime - i * 2000), Math.random() * 100]);
    }
    let graph = new Dygraph(document.getElementById("graph7"), data, {
      title: 'Real-Time Graph',
      xlabel: 'Time',
      ylabel: 'Value',
      labels: ['Time', 'Value'],
      colors: ['blue'],
      legend: 'always',
    });
    setInterval(() => {
      let newTime = new Date();  
      let newValue = Math.random() * 100;  
      data.push([newTime, newValue]);  
      if (data.length > 30) data.shift();  
      graph.updateOptions({ file: data });  
    }, 2500);
  });
</script>

Use Cases

Dygraphs is a powerful and lightweight charting library that is best suited for interactive time-series visualizations.

Some common possible use cases are:

  1. Visualization of financial data
  • Can be used to visualize stock market trends, cryptocurrency price changes or historical financial trends
  • How: Dygraphs allows for addition of multiple data series, which helps compare prices. Zooming and panning helps to analyze trends over time.
  1. Real-Time Data Monitoring for Sensors
  • Can be implemented for weather readings, device sensor readings etc.
  • How: Dygraphs supports real-time updates smoothly.
  1. Website Traffic and Analytics
  • Can be used for monitoring user engagement, server response times and website visits.
  • How: Dygraphs supports CSV and JSON data sources.
  1. Scientific and research data
  • Can be used for astronomical research, climate data analysis etc.
  • How: Dygraphs works well with large datasets without lag. It can also plot multiple variables in the same graph to analyze trends.

Conclusion

Dygraphs is a powerful and lightweight JavaScript library that makes it easy to visualize large time-series datasets with interactive features. Dygraphs provides a solution, whether you need real-time updates, zooming and panning, or multi-axis support for dynamic data visualization.

With its ability to work with huge datasets, support for different data formats, and synchronization capabilities, Dygraphs is an excellent choice for anyone who deals with time series data and is looking for a charting library that is customizable and easy to embed.


Video Submission


References

Dygraphs

Website: Website
Documentation: Dygraphs
CDN: UNPKG

Website building

Template used: Template
Tutorial playlist: Playlist