Skip to content

Source Data in Client Side JavaScript Libraries

airosa edited this page Mar 18, 2013 · 2 revisions

Source Data for Client Side JavaScript Libraries

Following is a brief overview of the data handling functionality in some popular JavaScript client libraries. Most of these libraries are featured in the "Data" section of JSDB.IO "The Database of JavaScript Libraries" (see http://www.jsdb.io/data).

In a summary all the libraries process source data from a JavaScript data array. Data array contains either objects (Rickshaw and Morris.js) or arrays (Dygraph, g.raphael and DataTables). D3 and Flot can process both. With the exception of D3 all the other libraries display the data values directly. D3 uses optional functions to access the values. This adds great flexibility to D3 visualisations.

Visualization libraries

D3 is "a JavaScript Visualization Library for HTML and SVG". D3 is extremely comprehensive but it is also more complex than other comparable visualization libraries.

The D3 interface to source data is the "data" function. Data function accepts two arguments "values" and "key":

"Joins the specified array of data with the current selection. The specified values is an array of data values, such as an array of numbers or objects, or a function that returns an array of values. If a key function is not specified, then the first datum in the specified array is assigned to the first element in the current selection, the second datum to the second selected element, and so on."

D3 works with arrays of data values but allows much flexibility with the way the data values are used. Basically when data values are use (e.g. as an argument to the "text" function) D3 will evaluate an optional function for each data value. This allows great flexibility with the data values.

Following example draws a simple bar chart:

var data = [4, 8, 15, 16, 23, 42];
var chart = d3.select("body").append("div").attr("class", "chart");

chart.selectAll("div")
    .data(data)
  .enter().append("div")
    .style("width", function(d) { return d * 10 + "px"; })
    .text(function(d) { return d; });

Data is a simple array of numbers but it be an array objects or other types. Data is joined to the chart with the data function. Following "enter" function will pass each data value as an argument "d" to the "style" and "text" functions.

Rickshaw is a "JavaScript toolkit for creating interactive time series graphs". Here is a simple example:

var graph = new Rickshaw.Graph( {
  element: document.querySelector('#graph'),
  series: [
    {
      color: 'steelblue',
      data: [ { x: 0, y: 23}, { x: 1, y: 15 }, { x: 2, y: 79 } ]
    }, {
      color: 'lightblue',
      data: [ { x: 0, y: 30}, { x: 1, y: 20 }, { x: 2, y: 64 } ]
    }
  ]
} );

graph.render();

The "Graph" function accepts an object as the argument with "series" as a property:

Array of objects containing series data to plot. Each object should contain data at a minimum, an array of objects each with x and y properties. Optionally send a name and color as well. Some renderers and extensions may also support additional keys.

Flot is a "pure JavaScript plotting library for jQuery, with a focus on simple usage, attractive looks and interactive features".

Flot provides a "plot" function:

var plot = $.plot(placeholder, data, options)

The data is an array of data series. A series can either be raw data or an object with properties. The raw data format is an array of points:

[ [1, 3], [2, 14.01], [3.5, 3.14] ]

The format of a single series object is as follows:

[ { label: "Foo", data: [ [10, 1], [17, -14], [30, 5] ] },
  { label: "Bar", data: [ [11, 13], [19, 11], [30, -7] ] }
]

Morris.js claims that "good-looking charts shouldn't be difficult". It is another JavaScript library for drawing charts. Simple example:

new Morris.Line({
  // ID of the element in which to draw the chart.
  element: 'myfirstchart',
  // Chart data records -- each entry in this array corresponds to a point on
  // the chart.
  data: [
    { year: '2008', value: 20 },
    { year: '2009', value: 10 },
    { year: '2010', value: 5 },
    { year: '2011', value: 5 },
    { year: '2012', value: 20 }
  ],
  // The name of the data record attribute that contains x-values.
  xkey: 'year',
  // A list of names of data record attributes that contain y-values.
  ykeys: ['value'],
  // Labels for the ykeys -- will be displayed when you hover over the
  // chart.
  labels: ['Value']
});

In morris.js the chart data and options are specified in an object. The data property is "This is an array of objects, containing x and y attributes as described by the xkey and ykeys options." Property "ykeys" is "A list of strings containing names of attributes that contain Y values (one for each series of data to be plotted)." and property "xkey" is "A string containing the name of the attribute that contains date (X) values.".

Dygraphs provides "Interactive visualizations of time series using JavaScript and the HTML canvas tag. The dygraphs JavaScript library produces interactive, zoomable charts of time series." Simple example:

g = new Dygraph(
      document.getElementById("div"),
      data,
      { options }
    );

The data values are provided with the "data" parameter. Dygraphs supports five types of input: CSV, URL (returns CSV), array (native format), function (returns csv etc.) and DataTable (from Google Visualization Library). Here's an example of data in array "native format":

 g = new Dygraph(
       document.getElementById("graphdiv2"),
       [
         [1,10,100],
         [2,20,80],
         [3,50,60],
         [4,70,80]
       ],
       {
         labels: [ "x", "A", "B" ]
       }
     );

gRaphaël’s goal is to "help you create stunning charts on your website". It is based on Raphaël graphics library. Simple example:

// Creates canvas 640 × 480 at 10, 50
var r = Raphael(10, 50, 640, 480);

// Creates line chart at coordinates (0,0) with width and height of 99
// Values to plot on x-axis are [1,2,3,4,5] and values to plot on y-axis
// are in arrays.
r.linechart(
  0, 0, 99, 99,
  [1,2,3,4,5],
  [
    [1,2,3,4,5],
    [1,3,9,16,25],
    [100,50,25,12,6]
  ],
  {smooth: true, colors: ['#F00', '#0F0', '#FF0'], symbol: 'circle'}
);

Data values are provided in arrays to all supported charts (pie, bar, dot etc.).

Chart.js provides "easy, object orientated client side graphs for designers and developers". Following is an example of a line chart. It will draw a line chart with two lines.

var data = {
    labels : ["January","February","March","April","May","June","July"],
    datasets : [
        {
            fillColor : "rgba(220,220,220,0.5)",
            strokeColor : "rgba(220,220,220,1)",
            pointColor : "rgba(220,220,220,1)",
            pointStrokeColor : "#fff",
            data : [65,59,90,81,56,55,40]
        },
        {
            fillColor : "rgba(151,187,205,0.5)",
            strokeColor : "rgba(151,187,205,1)",
            pointColor : "rgba(151,187,205,1)",
            pointStrokeColor : "#fff",
            data : [28,48,40,19,96,27,100]
        }
    ]
}

new Chart(ctx).Line(data,options);

Data is provided in an array of datasets. Each dataset contains an array of data values. Line, bar and radar charts use the similar data structures.

Table libraries

DataTables is "a plug-in for the jQuery Javascript library. It is a highly flexible tool, based upon the foundations of progressive enhancement, which will add advanced interaction controls to any HTML table." It provides very comprehensive library of functionality for HTML tables (pagination, filtering, sorting etc.).

DataTables supports following data sources: DOM, JavaScript array and ajax (with and without server side control). Ajax support is based on arrays in JSON.

Simple example:

$(document).ready(function() {
    $('#demo').html( '<table cellpadding="0" cellspacing="0" border="0" class="display" id="example"></table>' );
    $('#example').dataTable( {
        "aaData": [
            /* Reduced data set */
            [ "Trident", "Internet Explorer 4.0", "Win 95+", 4, "X" ],
            [ "Trident", "Internet Explorer 7.0", "Win XP SP2+", 7, "A" ],
            [ "Gecko", "Firefox 1.5", "Win 98+ / OSX.2+", 1.8, "A" ],
            [ "Webkit", "Safari 1.2", "OSX.3", 125.5, "A" ],
        ],
        "aoColumns": [
            { "sTitle": "Engine" },
            { "sTitle": "Browser" },
            { "sTitle": "Platform" },
            { "sTitle": "Version", "sClass": "center" },
            { "sTitle": "Grade", "sClass": "center" }
        ]
    } );
} );

DataTable function accepts an object as the only argument. Property "aaData" contains the data values in arrays.

Other libraries

Crossfilter is a "a JavaScript library for exploring large multivariate datasets in the browser. Crossfilter supports extremely fast (<30ms) interaction with coordinated views, even with datasets containing a million or more records". Simple example:

var payments = crossfilter([
  {date: "2011-11-14T16:17:54Z", quantity: 2, total: 190, tip: 100, type: "tab"},
  {date: "2011-11-14T16:28:54Z", quantity: 1, total: 300, tip: 200, type: "visa"},
  {date: "2011-11-14T16:30:43Z", quantity: 2, total: 90, tip: 0, type: "tab"},
  {date: "2011-11-14T16:54:06Z", quantity: 1, total: 100, tip: 0, type: "cash"},
  {date: "2011-11-14T17:22:59Z", quantity: 2, total: 90, tip: 0, type: "tab"},
  {date: "2011-11-14T17:25:45Z", quantity: 2, total: 200, tip: 0, type: "cash"},
]);

Crossfilter function constructs a new crossfilter. Data values can be an array of JavaScript objects or primitives. Dimension function create a new dimension with a value accessor function:

var paymentsByTotal = payments.dimension(function(d) { return d.total; });

Dimensions can be used to filter the data records in a crossfilter:

// selects payments whose total is between 100 and 200
paymentsByTotal.filter([100, 200]); 
// selects payments whose total equals 120
paymentsByTotal.filter(120);
// the top four payments, by total
var topPayments = paymentsByTotal.top(4);

Crossfilter supports also grouping data records by dimensions:

// count payments by dollar amount
var paymentGroupsByTotal = paymentsByTotal.group(function(total) { return Math.floor(total / 100); }); 

Clone this wiki locally