Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Creating Bar Chart using D3.JS

4.44/5 (5 votes)
25 Aug 2014CPOL3 min read 32.7K  
Creating Bar Chart from D3JS using CSV Data

Introduction

This tip is all about how to use your data from various resources and generate some charts according to your application requirement. In this post, I am using simple CSV data and D3JS for creating charts.

Agenda

  • Overview
  • Introduction | D3JS
  • Problem
  • Solution | Snippet
    • HTML | Snippet
    • JS | 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, etc. in data visualization (in generating charts like bar, pie, line charts, etc. and diagrams) according to the requirements.

This creates problems for developers as 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 is required?
  • How to parse data?
  • How to convert data from one to another form?
  • How to represent?
  • Etc.

So in this tip, I’ll try to make explain it and present a demo on it.

Image 1

So, get ready for some creative and graphics work.

Introduction | D3JS

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

One of the major advantages of D3JS is that you don’t need to give too much to go through it, as it is a part of JavaScript and uses 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 component.

I hope this much introduction of 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, etc.

Problem

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

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

Image 2

Solution | Snippet

The solution is given below.

(By only using HTML, CSS and D3JS)

Image 3

HTML | Snippet

HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
  <head>
     <title>Bar Chart</title>
     <meta http-equiv="X-UA-Compatible" content="IE=9">
     <link href="Style1.css" type="text/css" />
     
  </head>
  <body>
    <div id="chart"></div>
    <script src="http://d3js.org/d3.v2.min.js"></script>
    <script>
        function renderChart() {

          //  var width = 1020,
          //      height = 720,
            var data = d3.csv.parse(d3.select('#csv').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")
           
            // Vertical-align: middle
           .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) // padding-left
           .attr("dy", ".35em") // vertical-align: middle
           .attr("text-anchor", "start") // text-align: right
           .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>

     // CSV Data
    <script id="csv" type="text/csv">Name,Salary(PM)
    A, 21k
    B, 6k
    C, 17k
    D, 12k
    E, 15k
    F, 18k
    G, 14k
    H, 19k
    I, 11k
    </script>
    <script>  renderChart();</script>
  </body>
</html>

JS | Snippet

JS code is embedded into HTML snippet.

CSS | Snippet

CSS
html, body
{
}

#chart
{
    width:100%;
    border:1px solid;
}

#csv
{
    width: 560;
    height: 86;
    overflow:hidden;
}

Output

Image 4

Conclusion

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 tip. I’ll write some introductory part of D3JS and its related content in separate articles soon.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)