Creating Bar Chart From D3JS Using JSON Data

This article is all about how to use your data from various resources and generate some charts depending on your application requirements. In this article I am using simple JSON data and D3JS for creating charts.

Outlines

  • Overview
  • Introduction | D3JS
  • Problem
  • Solution | Snippet
    • HTML | Snippet
    • JavaScript | Snippet
    • CSS | Snippet
  • Output
  • Reference Examples
  • Summary

Overview

In many applications, sometimes we need to use data from JSON files, SQL Server tabular data, CSV data, flat file and so on in data visualization (in generating charts like bar, pie, line charts and so on and diagrams) depending on the requirements.

This creates problems for developers since usually they are unfamiliar with:

  • How to do it
  • What they need to use
  • The better way of doing that
  • What kind of rough data is required
  • How to parse Data
  • How to convert data from one to another format
  • How to represent it

And so on.

So in this article I'll try to explain it and present a demo of it.



So get ready for some creative and graphics work.

Introduction | D3JS

D3JS is a JavaScript library for data visualization mostly. From data visualization I mean data and information representation in the forms of charts (Bar, Pie, line, Area, Scatter, Histogram, Donut, Dendogram and so on).

D3JS is widely used for its well-defined functionality and its workflow simplicity. In D3JS we need to use a few properties related to the respective chart and then the work is over.

One of the major advantages of D3JS is that you don't need to give too much to go through it, since it is a part of JavaScript and uses a similar operation mode and functioning like it. So if you are familiar with JavaScript then it's for you.

What you need to do is simply embed your JavaScript in your simple HTML code and you're done. For decoration and formatting you can use CSS and its related components.

I hope that much of an introduction to D3JS will be enough at this level. I'll try to write a basic introductory article on D3JS containing features, properties, application areas, advantages, scope and so on.

Problem

Suppose you have a humongous collection of data such as of Population, account details, e-commerce, budgeting, surveys and so on in rough form and you want to convert it into something better and easy to represent and understand. Then Data Visualization is the best way to represent, understand and summarize it.

You don't need any extra effort, just write a few lines of code and your visualization of that rough data is completed.



Solution | Snippet

The solution is given below.

(By only using HTML, CSS and D3JS.)


  • HTML | Snippet

Here's a HTML Snippet with a JavaScript Snippet:

  1. <head id="Head1" runat="server">  
  2.      <title>Bar Chart</title>  
  3.      <meta http-equiv="X-UA-Compatible" content="IE=9">  
  4.      <link href="../../Content/Style.css"" type="text/css" />  
  5.      <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>  
  6.      <script>  
  7.          $(function () {  
  8.              var SALARY = [];  
  9.   
  10.              $.getJSON('SALARY.json', function (data) {  
  11.                  $.each(data.SALARY, function (i, f) {  
  12.                      var tblRow = "<tr>" + "<td>" + f.Name + "</td>" +  
  13.            "<td>" + f.Salary(PM) + "</td>" + "</tr>"  
  14.                      $(tblRow).appendTo("#Salary tbody");  
  15.                  });  
  16.              });  
  17.          });  
  18. </script>  
  19.   
  20. </head>  
  21.   
  22.     <form id="form1" runat="server">    
  23.      <div id="chart"></div>  
  24.     <script src="http://d3js.org/d3.v2.min.js" type=""></script>  
  25.     <script>  
  26.         function renderChart() {  
  27.   
  28.             //  var width = 1020,  
  29.             //      height = 720,  
  30.             var data = d3.json.parse(d3.select('#json').text());  
  31.             var valueLabelWidth = 40; // space reserved for value labels (right)  
  32.             var barHeight = 20; // height of one bar  
  33.             var barLabelWidth = 100; // space reserved for bar labels  
  34.             var barLabelPadding = 5; // padding between bar and bar labels (left)  
  35.             var gridLabelHeight = 18; // space reserved for gridline labels  
  36.             var gridChartOffset = 3; // space between start of grid and first bar  
  37.             var maxBarWidth = 420; // width of the bar with the max value  
  38.   
  39.             // Accessor functions   
  40.             var barLabel = function (d) { return d['Name']; };  
  41.             var barValue = function (d) { return parseFloat(d['Salary(PM)']); };  
  42.   
  43.             // Scales  
  44.             var yScale = d3.scale.ordinal().domain(d3.range(0, data.length)).rangeBands([0, data.length * barHeight]);  
  45.             var y = function (d, i) { return yScale(i); };  
  46.             var yText = function (d, i) { return y(d, i) + yScale.rangeBand() / 2; };  
  47.             var x = d3.scale.linear().domain([0, d3.max(data, barValue)]).range([0, maxBarWidth]);  
  48.   
  49.             // Svg container element  
  50.             var chart = d3.select('#chart').append("svg")  
  51.            .attr('width', maxBarWidth + barLabelWidth + valueLabelWidth)  
  52.            .attr('height', gridLabelHeight + gridChartOffset + data.length * barHeight);  
  53.   
  54.             // Grid line labels  
  55.             var gridContainer = chart.append('g')  
  56.             .attr('transform', 'translate(' + barLabelWidth + ',' + gridLabelHeight + ')');  
  57.             gridContainer.selectAll("text").data(x.ticks(10)).enter().append("text")  
  58.            .attr("x", x)  
  59.            .attr("dy", -3)  
  60.            .attr("text-anchor", "middle")  
  61.            .text(String);  
  62.   
  63.             // Vertical grid lines  
  64.             gridContainer.selectAll("line").data(x.ticks(10)).enter().append("line")  
  65.            .attr("x1", x)  
  66.            .attr("x2", x)  
  67.            .attr("y1", 0)  
  68.            .attr("y2", yScale.rangeExtent()[1] + gridChartOffset)  
  69.            .style("stroke", "#ccc");  
  70.   
  71.             // Bar labels  
  72.             var labelsContainer = chart.append('g')  
  73.            .attr('transform', 'translate(' + (barLabelWidth - barLabelPadding) + ',' + (gridLabelHeight + gridChartOffset) + ')');  
  74.             labelsContainer.selectAll('text').data(data).enter().append('text')  
  75.            .attr('y', yText)  
  76.            .attr('stroke', 'none')  
  77.            .attr('fill', 'black')  
  78.            .attr("dy", ".35em")  
  79.   
  80.             // Vertical-align: middle  
  81.            .attr('text-anchor', 'end')  
  82.            .text(barLabel);  
  83.   
  84.             // Bars  
  85.             var barsContainer = chart.append('g')  
  86.             .attr('transform', 'translate(' + barLabelWidth + ',' + (gridLabelHeight + gridChartOffset) + ')');  
  87.             barsContainer.selectAll("rect").data(data).enter().append("rect")  
  88.            .attr('y', y)  
  89.            .attr('height', yScale.rangeBand())  
  90.            .attr('width', function (d) { return x(barValue(d)); })  
  91.            .attr('stroke', 'Gray')  
  92.            .attr('fill', 'YellowGreen');  
  93.   
  94.             // Bar value labels  
  95.             barsContainer.selectAll("text").data(data).enter().append("text")  
  96.            .attr("x", function (d) { return x(barValue(d)); })  
  97.            .attr("y", yText)  
  98.            .attr("dx", 3)   
  99.            .attr("dy", ".35em")   
  100.            .attr("text-anchor", "start")   
  101.            .attr("fill", "black")  
  102.            .attr("stroke", "none")  
  103.            .text(function (d) { return d3.round(barValue(d), 2); });  
  104.   
  105.             // Start line  
  106.             barsContainer.append("line")  
  107.            .attr("y1", -gridChartOffset)  
  108.            .attr("y2", yScale.rangeExtent()[1] + gridChartOffset)  
  109.            .style("stroke", "#000");  
  110.   
  111.         }  
  112.   
  113.     </script> 

// JSON Data

  1. <!-- <script id="json" type="json/text">Name,Salary(PM) -->  
  2. <script id="json" type="text/json">   
  3.       
  4.         [  
  5.          { "Name": "A",  
  6.              "Salary": "21"  
  7.          },  
  8.          { "Name": "B",  
  9.              "Salary": "6"  
  10.          },  
  11.          { "Name": "C",  
  12.              "Salary": "17"  
  13.          },  
  14.          { "Name": "D",  
  15.              "Salary": "12k"  
  16.          },  
  17.          { "Name": "E",  
  18.              "Salary": "15"  
  19.          },  
  20.          { "Name": "F",  
  21.              "Salary": "18"  
  22.          }  
  23.          { "Name": "G",  
  24.              "Salary": "14"  
  25.          }  
  26.          { "Name": "H",  
  27.              "Salary": "19"  
  28.          }  
  29.          { "Name": "I",  
  30.              "Salary": "11"  
  31.          }  
  32.   
  33.   
  34.         ]  
  35.    
  36. </script>   
  37.     
  38.  <script> renderChart(); </script> 
  • JavaScript | Snippet

You can find the JavaScript snippet in the HTML snippet.

  • CSS | Snippet
  1. HTML, body {  
  2. }  
  3.   
  4. #chart  
  5. {  
  6.     width:100%;  
  7.     border:0px solid;  
  8. }  
  9.   
  10. #json  
  11. {  
  12.     width: 560;  
  13.     height: 86;  
  14.     overflow:hidden;  

Output



Reference Example

For connecting this article to my previous article that was about "Creating Bar Chart using D3.JS and CSV Data", please visit:

http://www.c-sharpcorner.com/UploadFile/2072a9/creating-bar-chart-from-d3js-using-csv-data/

Summary

So, for now you will have at least a feel of why data visualization is necessary, why to do that and what we need to use for visualization. If you have any query related to this article, charts, data visualization, D3Js then write back to me, I would love to answer your queries.

I hope you enjoyed this article. I'll write some introductory part of D3JS and its related content in separate articles soon.

Up Next
    Ebook Download
    View all
    Learn
    View all