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

JSON Bar Chart using d3js AC

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 data visualization, then obviously you find most of the libraries that are not free. But D3.js is an 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.

What is JSON?

JSON stands for JavaScript Object Notation. It is text-based data used to represent structured data. It is mostly used to send data in web and mobile applications.  For example, if I want to authorize login to the user then I will use JSON format. Another example is if I want to show us something then also I will use JSON format data. It makes the development of applications easy and fast.

 

Step 1: Integrate the D3.js file.

First of all, for drawing a bar chart in d3.js you are 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 the axis for the chart.

In this step, you will define the axis for the SVG. Doing this will fit the data in the JSON automatically and also name the x and y-axis. Use the following code to draw an 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 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 and height. Next, the append(g) will do grouping and shift the SVG from left and top with the defined pixel.

Step 5: Reading and mapping of JSON data

Now the next step before the 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 groupings done first on the x-axis and the other on the y-axis.  After that bars from the data are 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 has 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 queries on d3.js please contact us. We are always ready to help you. You can also like our official Data Science Learner Page.

Source

D3.js Offical Website

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.

Meet Sukesh ( Chief Editor ), a passionate and skilled Python programmer with a deep fascination for data science, NumPy, and Pandas. His journey in the world of coding began as a curious explorer and has evolved into a seasoned data enthusiast.
 
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner