Creating Bar Chart From D3JS Using JSON Data

Introduction

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.

Demo

So get ready for some creative and graphics work.

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, Dendrogram, 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 functions 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 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.

Rough data

Solution | Snippet

The solution is given below.

(By only using HTML, CSS and D3JS.)

Visualized  Data

HTML | Snippet

Here's a HTML Snippet with a JavaScript Snippet.

<head id="Head1" runat="server">
    <title>Bar Chart</title>
    <meta http-equiv="X-UA-Compatible" content="IE=9">
    <link href="../../Content/Style.css" type="text/css" />
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
    <script>
        $(function () {
            var SALARY = [];
            $.getJSON('SALARY.json', function (data) {
                $.each(data.SALARY, function (i, f) {
                    var tblRow = "<tr>" +
                        "<td>" + f.Name + "</td>" +
                        "<td>" + f.Salary(PM) + "</td>" +
                        "</tr>";
                    $(tblRow).appendTo("#Salary tbody");
                });
            });
        });
    </script>
</head>
<form id="form1" runat="server">
    <div id="chart"></div>
    <script src="http://d3js.org/d3.v2.min.js" type="text/javascript"></script>
    <script>
        function renderChart() {
            var data = d3.json.parse(d3.select('#json').text());
            var valueLabelWidth = 40; // space reserved for value labels (right)
            var barHeight = 20; // height of one bar
            var barLabelWidth = 100; // space reserved for bar labels
            var barLabelPadding = 5; // padding between bar and bar labels (left)
            var gridLabelHeight = 18; // space reserved for gridline labels
            var gridChartOffset = 3; // space between start of grid and first bar
            var maxBarWidth = 420; // width of the bar with the max value
            // Accessor functions
            var barLabel = function (d) { return d['Name']; };
            var barValue = function (d) { return parseFloat(d['Salary(PM)']); };
            // Scales
            var yScale = d3.scale.ordinal().domain(d3.range(0, data.length)).rangeBands([0, data.length * barHeight]);
            var y = function (d, i) { return yScale(i); };
            var yText = function (d, i) { return y(d, i) + yScale.rangeBand() / 2; };
            var x = d3.scale.linear().domain([0, d3.max(data, barValue)]).range([0, maxBarWidth]);
            // SVG container element
            var chart = d3.select('#chart').append("svg")
                .attr('width', maxBarWidth + barLabelWidth + valueLabelWidth)
                .attr('height', gridLabelHeight + gridChartOffset + data.length * barHeight);
            // Grid line labels
            var gridContainer = chart.append('g')
                .attr('transform', 'translate(' + barLabelWidth + ',' + gridLabelHeight + ')');
            gridContainer.selectAll("text").data(x.ticks(10)).enter().append("text")
                .attr("x", x)
                .attr("dy", -3)
                .attr("text-anchor", "middle")
                .text(String);
            // Vertical grid lines
            gridContainer.selectAll("line").data(x.ticks(10)).enter().append("line")
                .attr("x1", x)
                .attr("x2", x)
                .attr("y1", 0)
                .attr("y2", yScale.rangeExtent()[1] + gridChartOffset)
                .style("stroke", "#ccc");
            // Bar labels
            var labelsContainer = chart.append('g')
                .attr('transform', 'translate(' + (barLabelWidth - barLabelPadding) + ',' + (gridLabelHeight + gridChartOffset) + ')');
            labelsContainer.selectAll('text').data(data).enter().append('text')
                .attr('y', yText)
                .attr('stroke', 'none')
                .attr('fill', 'black')
                .attr("dy", ".35em")
                .attr('text-anchor', 'end')
                .text(barLabel);
            // Bars
            var barsContainer = chart.append('g')
                .attr('transform', 'translate(' + barLabelWidth + ',' + (gridLabelHeight + gridChartOffset) + ')');
            barsContainer.selectAll("rect").data(data).enter().append("rect")
                .attr('y', y)
                .attr('height', yScale.rangeBand())
                .attr('width', function (d) { return x(barValue(d)); })
                .attr('stroke', 'Gray')
                .attr('fill', 'YellowGreen');
            // Bar value labels
            barsContainer.selectAll("text").data(data).enter().append("text")
                .attr("x", function (d) { return x(barValue(d)); })
                .attr("y", yText)
                .attr("dx", 3)
                .attr("dy", ".35em")
                .attr("text-anchor", "start")
                .attr("fill", "black")
                .attr("stroke", "none")
                .text(function (d) { return d3.round(barValue(d), 2); });
            // Start line
            barsContainer.append("line")
                .attr("y1", -gridChartOffset)
                .attr("y2", yScale.rangeExtent()[1] + gridChartOffset)
                .style("stroke", "#000");
        }
    </script>
</form>

// JSON Data

<!-- <script id="json" type="json/text">Name,Salary(PM) -->    
<script id="json" type="text/json">     
    [    
        { "Name": "A", "Salary": "21" },    
        { "Name": "B", "Salary": "6" },    
        { "Name": "C", "Salary": "17" },    
        { "Name": "D", "Salary": "12k" },    
        { "Name": "E", "Salary": "15" },    
        { "Name": "F", "Salary": "18" },    
        { "Name": "G", "Salary": "14" },    
        { "Name": "H", "Salary": "19" },    
        { "Name": "I", "Salary": "11" }    
    ]    
</script>     
      
<script> 
    renderChart(); 
</script>

JavaScript | Snippet

You can find the JavaScript snippet in the HTML snippet.

CSS | Snippet

HTML, body {    
}    
#chart {    
    width: 100%;    
    border: 0px solid;    
}    
#json {    
    width: 560px;    
    height: 86px;    
    overflow: hidden;    
}

Output

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.