Data Streaming

Plotting Real-time Data of Financial Performance with NVD3

0 MIN READ • Apr 24, 2015

Tracking financial data is just one of the many sets of data we can collect, stream, and visualize. In this blog post, we're going to take profit earned by drivers, then chart that data on a real-time, NVD3 visualization with AngularJS.

Take this PubNub application for example.

pnub

Over time, the bullet charts fill-in when each driver completes a route. The shaded areas can represent the minimum amount a driver has ever made, the average amount, and the maximum amount over a period of one-day. The pointer on the graph can represent a milestone.In this case it means the minimum amount necessary to meet the costs of the driver.

Setup

The setup for the index.haml is short. HAML is a pre-compiled version of HTML. It can be easier to read and write. First take a look at the dependencies:

1.haml
%script(src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.min.js")
%script(src="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.1.15-beta/nv.d3.min.js")
%script(src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.min.js")
%script(src="http://cdn.pubnub.com/pubnub.min.js")
%script(src="pubnub-angular.js")
%link(rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.1.15-beta/nv.d3.min.css")
  • d3 allows you to draw graphs.
  • NVD3 makes those graphs pretty.
  • angular is used for it’s powerful views and controllers.
  • pubnub.min.js supports pubnub-angular.
  • pubnub-angular.js is used for real-time communication for Angular.
  • nv.d3.min.css provides styles for the graph.
logos

Note that pubnub-angular.js is in the directory. You can get this file by using Bower and typing bower install pubnub-angular. This will put the file in a bower_components package. Just take the file out of there. Next set-up the Angular app.

2.haml
%body(ng-app="exampleApp")
  %div(ng-controller="exampleCtrl")
    %h1 example Drivers

This takes care of the basics for HTML/HAML. Next you need to set-up the JavaScript.

3.haml
%script(src="driver.js")

Make sure to include the driver.js file into the html.

The JavaScript

In the first line you declare the Angular app.

4.js
angular.module("exampleApp", ['pubnub.angular.service'])

Then without a semi-colon, use dot notation to instantiate the controller.

5.js
.controller("exampleCtrl", ['$rootScope', '$scope', '$http', 'PubNub', function ($rootScope, $scope, $http, PubNub) {

In this example the array syntax for injecting services was used. This style is useful for production minification. This is a lot. You should run the app thus far to make sure there are no errors.

Basic Data

Set up a basic structure for the drivers. In this case there are 4 drivers. The requirements are shown here in the JSON. Put these objects side-by-side in an array.

6.js
{
  "driverId":1,
  "min": 60,
  "max": 350,
  "previousDay": 160,
  "mean": 120,
  "numberDays": 6,
  "currentTotal": 0
}

More JS

Cutting back to the JavaScropt, use the $http service to pull in the static JSON data.

7.js
$http.get('example_drivers.json')
  .success(function(data) {
    main(data);
  });

Notice that it passes the data to the main() method. As with other asynchronous calls, you need to use some sort of callback. That’s what main() is for. Name the data as $scope.drivers. And pass those drivers onto a graph.

8.js
function main(data) {
  $scope.drivers = data;
  graphs($scope.drivers);
  pubNubInit();
}

NVD3

In the graphs function use the forEach method on the JSON array.

9.js
data.forEach(function(driver) {
  nv.addGraph(function() {
    chart = nv.models.bulletChart();
    d3.select('#chart'+driver.driverId)
        .datum(processChart(driver))
        .transition().duration(1000)
        .call(chart);
    return chart;
  });
});

In this function you declare a bulletChart, the style of chart for this app. D3 selects the id of the appropriate SVG, more on that later. D3 takes an object for its configuration, in this case you use the processChart() method. The transition describes animations for the chart.

ng-repeat

Note that you declared $scope.drivers earlier. This means you can use this data with Angular. Back in index.haml….

10.haml
%div(ng-repeat="driver in drivers" style="height:100px;")
  %svg(id="chart{{driver.driverId}}")

This is the magic of Angular. It allows you to repeat the number of objects in the array. With each object you give an svg the ID of “chart<driver’s id number>”. For example “chart 1” for the first driver. This allows you to show 4 charts with two lines of code.

Listening with PubNub

Now set the graphs to listen for messages. Earlier you injected the PubNub service in the controller. Now you will use it.pubNubInit() is called from the main method.

To get your unique pub/sub keys, you’ll first need to sign up for a PubNub account. Once you sign up, you can get your unique PubNub keys in the PubNub Developer Dashboard. The Free plan gives you up to 200 MAU or 1 million transactions a month to build, test, and launch your messaging app.

11.js
if (!$rootScope.initialized) {
  PubNub.init({
    subscribe_key: 'subscribe_key',
    publish_key: 'publish_key'
  });
  $rootScope.initialized = true;

Subscribe to the channel.

12.js
PubNub.ngSubscribe({ channel: "example"});

Then use $rootScope to be able to manually drive the rest of the app on a message event.

13.js
$rootScope.$on(PubNub.ngMsgEv("example"), function(ngEvent, payload) {

With each message get the driver position and tally-up the fare they just acquired.

14.js
var driver_position_in_array = $scope.driver_message.driverId - 1;
var current_driver = $scope.drivers[driver_position_in_array];
current_driver.currentTotal += $scope.driver_message.fare;

With that information, add it to that driver’s chart.

15.js
d3.select('#chart'+current_driver.driverId)
  .datum(processChart(current_driver))
  .transition().duration(1000)
  .call(chart);

Now that you’re listening with PubNub, it’s time to send some messages!

Sending with PubNub

In the code example there is a file spoof.js. This spoofs various messages in under 40 lines of JavaScript. PubNub is that easy! You can simply use this file and change the various numbers and parameters for different results. In order to use the file, you need to have Node and NPM installed.

Go here if you need to install these and follow the tutorial. With node use npm install pubnub. Then type node spoof.js. That’s it! You’ll see your messages start sending.

pubnub

Help Running the Graph

Now that you’re sending messages you want the graph to be able to populate based on the data. Use python -m SimpleHTTPServer or simple open the index.html in your web-browser. You should see the graph populate as you send messages!

IoT
Apr 22, 2015

Displaying Tessel Temperature Data on a Live Chart | PubNub

How to use the Tessel Climate module, AngularJS, the NVD3 library, and PubNub to graph real-time Tessel temperature and humidity data over a WiFi network.
Michael Carroll
Michael Carroll
Geolocation
Apr 28, 2015

Broadcasting Geolocation Data: HTML5 Services and JS | PubNub

A walkthrough on how to detect and broadcast geolocation data in real time using JavaScript and HTML5 location services.
Michael Carroll
Michael Carroll
Oct 8, 2014

D3js: Data Visualization Eye Candy + Streaming JSON

We'll show you how to build real-time visualizations with D3js and PubNub, in this case streaming JSON to create a dynamic bubble chart.
Michael Carroll
Michael Carroll