JSON Bar Chart using d3js AC

How to Draw JSON Bar Chart using d3.js ? 5 Steps

Data Visualization is a must for the Data Scientist. It makes them easy for doing an analysis of the data. If you search for the best framework for the data visualization, then obviously you find most of the libraries that are not free. But D3.js is open source Javascript library for doing data visualization. In this article, you will know how to draw json bar chart using d3.js. Just follow the steps below to draw a beautiful bar chart.

Step 1: Integrate D3.js file.

First of all, for drawing a bar chart in d3.js you required to add js to the HTML page. You can directly integrate through CDN URL. Alternatively, you can download the latest version from their official URL. For this tutorial, I am using version 3.

<script src="https://d3js.org/d3.v3.min.js"></script>

Step 2:  Create variables for the chart

After integrating the d3.js on your web page. The next step is to define the basic variable for the width, height, x and y range of the variable. Add the following code to your webpage inside the <script></script> tag.

var margin  = {top: 20, right: 20, bottom: 100, left: 60},
        width   = 600 - margin.left - margin.right,
        height  = 400 - margin.top - margin.bottom,
        x       = d3.scale.ordinal().rangeRoundBands([0,width], 0.5),
        y       = d3.scale.linear().range([height,0]);

In the above code, I defined the variable margin, width, height,x and y ranges (Scaling). This is done to make sure that our bar chart looks good.

Step 3: Draw axis for the chart.

In this step, you will define the axis for the SVG. Doing this it will fit the data in the JSON automatically and also name the x and y-axis. Use the following code to draw axis on the chart.

  var xAxis   = d3.svg.axis()
        .scale(x)
        .orient("bottom");
  var yAxis   = d3.svg.axis()
        .scale(y)
        .orient("left")
        .ticks(5)
        .innerTickSize(-width)
        .outerTickSize(0)
        .tickPadding(10);

I defined two axis variables xAxis and yAxis and use the scale(x) and scale(y ) defined in step 2. The main thing the above code will do it will draw the levels on the x and y-axis

Step 4:  Create an SVG File.

After the step3, now I will create an SVG and define its attributes. Use the following code to draw an SVG.

var svg     = d3.select("#wordCountContainer")
        .append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

Let’s know about the above code. All the output after the assignment operator ( = ) will be assigned to the variable SVG. After selecting the id wordCountContainer an SVG will append inside it with the width, height. Next, the append(g) will do grouping and shifting the SVG from left and top with the defined pixel.

Step 5: Reading and mapping of JSON data

Now the next step before final execution is to read data from JSON and map the x and y domain from the data. You will read the JSON using d3.json() method. Continue the above code with the following code.

d3.json("data/contentWordCount.json", function (data)
    {
        x.domain(data.map(function (d)
        {
            return d.name;
        }));

        y.domain([0, d3.max(data, function (d)
        {
            return d.wc;
        })]);

        svg.append("g")
            .attr("class", "x axis")
            .attr("transform", "translate(0, " + height + ")")
            .call(xAxis)
            .selectAll("text")
            .style("text-anchor", "middle")
            .attr("dx", "-0.5em")
            .attr("dy", "-.55em")
            .attr("y", 30)
            .attr("transform", "rotate(0)" );

        svg.append("g")
            .attr("class", "y axis")
            .call(yAxis)
            .append("text")
            .attr("transform", "rotate(-90)")
            .attr("y", 5)
            .attr("dy", "0.8em")
            .attr("text-anchor", "end")
            .text("Word Count");

        svg.selectAll("bar")
            .data(data)
            .enter()
            .append("rect")
            .style("fill", "orange")
            .attr("x", function(d)
            {
                return x(d.name);
            })
            .attr("width", x.rangeBand())
            .attr("y", function (d)
            {
                return y(d.wc);
            })
            .attr("height", function (d)
            {
                return height - y(d.wc);
            })

The methods x.domain() and y.domain() methods map the data for the x and y-axis. There is two grouping done first on the x-axis and other on the y-axis.  After that bars from the data drawn using the method SVG.selectAll(“bar). The data(data) will choose the JSON data and append rectangles according to it.  There are four attributed defined inside the svg.selectAll(“bar”) and the map is done along with JSON data. If you want to know more about the above attributes and methods read the below article.

How to create a Simple D3.js Bar Chart? 

The following is the Full Code.

style.css

            svg {
			border: 1px solid #000;
		}
		body, html {
	    width: 100%;
	    height: 100%;
	    margin: 0 auto;
		}

		.graph {
		    width: auto;
		}

		.tooltip {
		    text-decoration: underline;
		}

		.axis {
		    font: 10px Georgia, Arial, sans-serif;
		}

		.axis path, .axis line {
		    fill: none;
		    stroke: #dadada;
		    shape-rendering: crispEdges;
		}

Inside the body tag.

<div class = "graph" id="wordCountContainer"></div>
var margin  = {top: 20, right: 20, bottom: 100, left: 60},
        width   = 600 - margin.left - margin.right,
        height  = 400 - margin.top - margin.bottom,
        x       = d3.scale.ordinal().rangeRoundBands([0,width], 0.5),
        y       = d3.scale.linear().range([height,0]);

//draw axis
    var xAxis   = d3.svg.axis()
        .scale(x)
        .orient("bottom");
	var yAxis   = d3.svg.axis()
        .scale(y)
        .orient("left")
        .ticks(5)
        .innerTickSize(-width)
        .outerTickSize(0)
        .tickPadding(10);

 var svg     = d3.select("#wordCountContainer")
        .append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

d3.json("contentWordCount.json", function (data)
    {
        x.domain(data.map(function (d)
        {
            return d.name;
        }));

        y.domain([0, d3.max(data, function (d)
        {
            return d.wc;
        })]);

        svg.append("g")
            .attr("class", "x axis")
            .attr("transform", "translate(0, " + height + ")")
            .call(xAxis)
            .selectAll("text")
            .style("text-anchor", "middle")
            .attr("dx", "-0.5em")
            .attr("dy", "-.55em")
            .attr("y", 30)
            .attr("transform", "rotate(0)" );

        svg.append("g")
            .attr("class", "y axis")
            .call(yAxis)
            .append("text")
            .attr("transform", "rotate(-90)")
            .attr("y", 5)
            .attr("dy", "0.8em")
            .attr("text-anchor", "end")
            .text("Word Count");

        svg.selectAll("bar")
            .data(data)
            .enter()
            .append("rect")
            .style("fill", "orange")
            .attr("x", function(d)
            {
                return x(d.name);
            })
            .attr("width", x.rangeBand())
            .attr("y", function (d)
            {
                return y(d.wc);
            })
            .attr("height", function (d)
            {
                return height - y(d.wc);
            });
		
})

The file contentWordCount.json have the following values.


[
{"name": "Original Word Count", "wc": 100},
{"name": "Model Word Count", "wc": 90 }
]

 

When you run the index.html file. You will see the following output.

json bar chart using d3
Output

I hope you learned how to create JSON Bar Chart using d3.js. If you have any query on d3.js please contact us. We are always ready to help you. You can also like our official Data Science Learner Page.

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

 
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner