Creating Bar Chart From D3JS Using CSV 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 CSV data and D3JS for creating charts.

Agenda

  • Overview
  • Introduction | D3JS
  • Problem
  • Solution | Snippet
    • HTML | Snippet
    • JavaScript | Snippet
    • CSS | Snippet
  • Output
  • Conclusion

Overview

In many applications, sometimes we need to use data from CSV files, SQL Server tabular data, JSON 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 don't know about:

  • How to do that?
  • What they need to use?
  • What will be the better way of doing that?
  • What kind of rough data required?
  • How to parse data?
  • How to convert data from one to another form?
  • How to represent?
And so on. So in this article I'll try to make explain it and present a demo on it.

data visualization

So get ready for some creative and graphics work.

Introduction | D3JS

D3JS is a JavaScript library used for data visualization mostly. From data visualization I mean data, information representation in forms of charts (Bar, Pie, line, Area, Scatter, Histogram, Donut and so on.) D3JS is widely used for its well-defined functionality and its work flow simplicity. In D3JS we need to use a few properties related to the respective chart and the work is over.

One of the major advantage 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 component.

I hope this 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 in an understandable form. 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 about that rough data is completed.

Data Visualization flow

Solution | Snippet

The solution is given below.

(By only using HTML, CSS and D3JS.)

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

    The JavaScript code is embedded into the HTML snippet.  

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

Output

CSS Snippet

Conclusion

So, for now you will have at least a feel of why data visualization is necessary, why to do it 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