Underscore.JS, developed by Jeremy Ashkenas in the year 2009, is a JavaScript library that has more than 100 inbuilt functions to manipulate data quickly and efficiently. These functions, based on the datatype they are used for, can be categorized as functions that can be used to manipulate:
  • Arrays
  • Objects
  • Arrays and objects (these functions are also called collections)
  • Other functions
These functions include simple functions, like the ones used for mapping data, filtering data, and so on, as well as complex functions, like the ones used for JavaScript templating, function binding, and so on. Underscore.JS also comes with two utility categories, namely:
  • Utility
  • Chaining
What makes Underscore.JS so useful is its ability to manipulate objects, arrays, and functions using just about 2-3 lines of code. Underscore simplifies work when you are working with a non-DOM code or with a complex MVC. For a developer who is familiar with JavaScript, switching to Underscore.JS comes without any hassles given the simplicity of its template. For a library that is just about 4kb in size, the Underscore library definitely includes quite a lot of functionality that helps create code that is concise and clearly readable.

Charting in Underscore.JS [using FusionCharts]

Underscore’s functions, when combined with the data visualization capabilities of FusionCharts, simplify processes like mapping data labels to data values and sorting data to create meaningful visualizations. Also, making the code short and less complex. To demonstrate how you can use FusionCharts and Underscore.JS together to create charts, we’ll create a sample of a column 2D chart. This chart showcases the average number of runs scored by a cricketer against the average number of runs scored by the opposition team. The chart will also have the half-century target mark. So let’s get started! Step 1: Adding the dependencies To add the dependencies, paste the following links to your file:
https://static.fusioncharts.com/code/latest/fusioncharts.js
https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js
https://csm.fusioncharts.com/projects/themes/hulk-light.js (optional)
Step 2: Creating the HTML elements Corresponding to the requirements for the sample, create the HTML elements using the code snippet given below:
<h3><font face="Roboto">
FusionCharts using UnderScore JS
</font>
</h3>
<div id="chart-container">
FusionCharts will render here...
</div>
Step 3: Calling the FusionCharts ready() method Call the FusionCharts ready() method that will be the entry point for the chart framework using the structure given below:
FusionCharts.ready(function() {
...
….
…..
//your code here
});
Step 4: Creating the chart instance To create the chart instance, add the code snippet given below within the ready() method:
var scoreCard = new FusionCharts({
      type: bar2d,
      renderAt: 'chart-container',
      width: '100%',
      height: '350',
      dataFormat: 'json',
      dataSource: …. 
//to be created later
});
Step 5: Preparing the chart data The Underscore.JS Utility Library lets you perform various operations on your data, like merging data arrays, creating data objects, sorting data within the objects, and so on. Click here to know more. Step 5.1: Creating data arrays and converting them into objects Create two arrays, one with the team names, or the labels, and another with the average number of runs, or the data values, and then convert them into objects. To do this, use the code snippet given below:
var a = ['Players standing {br} around between plays', 'Commercials', 'Replays', 'Gameplay', 'Coach Shots', 'Referee Shots', 'Halftime', 'Sideline player shots', 'On-screen promotions', 'Other'];
  var b = [35.5, 24.5, 10.7, 8.3, 4.9, 3.2, 3.2, 2.2, 2, 5.5];

  var t = _.object(a, b);
Step 5.2: Creating object arrays Create object arrays in order to map the data labels (the team names) with the data values (the average number of runs) and convert them into FusionCharts’ prescribed JSON data format for a single series chart. To do this, use the code snippet given below:
var maindata = [];

 for (var i = 0; i < a.length; i++) {
    var k = new Object();
    k.label = a[i];
    k.value = b[i];
    maindata.push(k);
}
Step 5.3: Sorting the objects Sort the objects according to the data values using Underscore’s sortBy collection. To do this, use the code line given below:
var sortedmaindata = _.sortBy(maindata, 'value').reverse();
The sortedmaindata variable now holds the sorted data values and their corresponding data labels. Step 5.4: Preparing the data source Pass the sortedmaindata variable as the value to FusionCharts’ data object along with defining the other cosmetics and functionalities of the chart. To do this, use the code given below:
var scoreCard = new FusionCharts({
      type: 'bar2d',
      renderAt: 'chart-container',
      width: '100%',
      height: '400',
      dataFormat: 'json',
      dataSource: {
        "chart": {
          "caption": "What actually happens in an NFL game",
          "captionAlignment": "left",
          "subcaption": "An NFL broadcast, minute by minute",
          "subCaptionFontSize": "13",
          "paletteColors": "#0075C2",
          "placeValuesInside": "0",
          "exportEnabled": "1",
          "theme": "hulk-light",
          "valuefontcolor": "#0000000",
          "yaxisminvalue": "0",
          "yaxismaxvalue": "40",
          "divlinealpha": "0",
          "showAlternateVGridColor": "0",
          "showYAxisValues": "1",
          "showPlotBorder": "0",
					
          "showYAxisLine": "1",
          "yAxisLineColor":"#000000",
          "numbersuffix": "%",
          "useRoundEdges": "1",
          "showLabels": "1"

        },
        "data": sortedmaindata,


      }

    })
Step 6: Rendering the chart Call the render() method from the FusionCharts API to render the chart. The complete code for this sample, also showing how the render() method will be used, is:
FusionCharts.ready(function() {

  var a = ['Players standing {br} around between plays', 'Commercials', 'Replays', 'Gameplay', 'Coach Shots', 'Referee Shots', 'Halftime', 'Sideline player shots', 'On-screen promotions', 'Other'];
  var b = [35.5, 24.5, 10.7, 8.3, 4.9, 3.2, 3.2, 2.2, 2, 5.5];

  var t = _.object(a, b);
  console.log(t);

  var maindata = [];


  for (var i = 0; i < a.length; i++) {
    var k = new Object();
    k.label = a[i];
    k.value = b[i];
    maindata.push(k);

  }
  //console.log(maindata);

  var sortedmaindata = _.sortBy(maindata, 'value').reverse();
  console.log(sortedmaindata);

  var scoreCard = new FusionCharts({
      type: 'bar2d',
      renderAt: 'chart-container',
      width: '100%',
      height: '400',
      dataFormat: 'json',
      dataSource: {
        "chart": {
          "caption": "What actually happens in an NFL game",
          "captionAlignment": "left",
          "subcaption": "An NFL broadcast, minute by minute",
          "subCaptionFontSize": "13",
          "paletteColors": "#0075C2",
          "placeValuesInside": "0",
          "exportEnabled": "1",
          "theme": "hulk-light",
          "valuefontcolor": "#0000000",
          "yaxisminvalue": "0",
          "yaxismaxvalue": "40",
          "divlinealpha": "0",
          "showAlternateVGridColor": "0",
          "showYAxisValues": "1",
          "showPlotBorder": "0",
					
          "showYAxisLine": "1",
          "yAxisLineColor":"#000000",
          "numbersuffix": "%",
          "useRoundEdges": "1",
          "showLabels": "1"

        },
        "data": sortedmaindata,


      }


    })
    .render();
});

Output

The output looks like the chart shown in the image below:

Troubleshooting

If you see any errors in your code or have trouble executing the above sample, refer to the fiddle sample. If you are stuck anywhere, drop us a line at [email protected] and we’ll be happy to help!

Take your data visualization to a whole new level

From column to donut and radar to gantt, FusionCharts provides with over 100+ interactive charts & 2,000+ data-driven maps to make your dashboards and reports more insightful

Explore FusionCharts

Leave a comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.