Data Visualization with D3 journal Part: 2

Salman khalid
3 min readJun 21, 2018

Visualise Data with a Bar Chart

This article is about the first project of data visualisation certification. It is about how to show United States GDP comparison chart over the years using bar chart. This kind of visualisation is commonly used to summarise a large amount of data in a visual, easily interpretable form. In our final graph, one can easily view all the variations in United States GDP over the period of time.

I divided this project into couple of small tasks which are listed as follows:

  1. Fetch Data from API

In the first step I called this API to fetch data relevant GDP data to be displayed as bar chart. I made an ajax request call for this purpose.

req=new XMLHttpRequest();
req.open("GET",'https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json',true);
req.send();
req.onload=function() {
// Call back function calls when request loaded
}

The second param in XMLHttpRequest ‘open’ method is taking a boolean. It makes this call ‘async’.

Once we have the data then we can move to the next steps which involved further processing this data to be displayed in our desired visual representation

2. Create ‘svg’

In this step I created an ‘svg’ instance which acts as a canvas for all further drawings and acts as a parent or container for all the shapes we want to add in the graph. It can be created like this:

const width = 900;
const height = 500;
const svg = d3.select("#main")
.append("svg")
.attr("width",width)
.attr("height",height);

3. Define ‘x’ and ‘y’ axis

Next, I have to define axis for the graph. It involved three further steps. In the first one, I have to create a scale which requires domain and range. As I have discussed this thing in my last article, domain is related to the data we want to visualise and range is dependent on the size of svg. So keeping these things in my mind first I calculated the min and max for time period which is being represented along x-axis.

const minYear =  d3.min(dataSet, function(d){ return getYearFromDate(d[0]); });      
const maxYear = d3.max(dataSet, function(d){ return getYearFromDate(d[0]); });

dataSet is an Array which contains all data including year and gdp. Next, I defined a scale using the above calculated values.

const padding = 70;
const xScale = d3.scaleLinear()
.domain([minYear, maxYear]).range([padding, w - padding]);

Now, we have all scale ready which we can use to create axis like this

const xAxis = d3.axisBottom(xScale).tickFormat(d3.format("d"));

In the above code, we are first creating a bottom aligned axis using the Scale which we created in the last step.

Now we just need to add this axis in our parent svg instance which we created couple of steps back.

svg.append("g")
.attr("transform", "translate(0," + (h - padding) + ")")
.attr("id","x-axis")
.call(xAxis);

Anchor point (0,0) for d3 drawing is top left. So in the above code we had to transform our axis on y axis according to the height of svg.

Likewise we can also create y-axis using all the same steps of x-axis.

const yScale = d3.scaleLinear()
.domain([0, d3.max(dataSet, (d) => d[1])])
.range([h - padding, padding]);
const yAxis = d3.axisLeft(yScale);svg.append('g')
.attr("transform", "translate("+padding+","+0+")")
.attr("id","y-axis")
.call(yAxis);

4. Create Bar Chart using ‘Rect’ shapes

Here we have to add ‘rect’ shpaes in svg according to the number of items present in dataSet. Here I also used ‘xScaleWidthfactor’ which is being calculated using total number of items and total width of axis. I also added two properties (“data-date” and “data-gdp”) which were needed by Test script privded by freeCodeCamp.

svg.selectAll("rect")
.data(dataSet)
.enter()
.append("rect")
.attr("x", (d, i) => {return xScale((i*xWidthFactor)+parseInt(minYear));})
.attr("y", (d, i) => {
return yScale(d[1]);
})
.attr("class","bar")
.attr("width", xScaleWidthfactor)
.attr("height", (d, i) => {
return (h - padding - yScale(d[1]));})
.attr("data-date",function(d,i){
return d[0];
})
.attr("data-gdp",function(d){
return d[1];
})

5. Add tool tip to display info related to each Bar graph

var tooltip = d3.select("body")
.append("div")
.attr("class", "toolTip")
.attr("id","tooltip");

Here we have created a tooltip on ‘body’ and now we will just hide/show it when mouse hover over any bar rect.

.on("mouseover", function(d,i){
tooltip
.style("left", d3.event.pageX - 100 + "px")
.style("top", d3.event.pageY - 80 + "px")
.style("display", "inline-block")
.html("Date: "+d[0])
.attr("data-date",d[0]);
})
.on("mouseout", function(d){ tooltip.style("display", "none");});

Above code will be added on each rect which we have created few steps back. Its using two events (“mouseover” and “mouseout” ) to achieve the desired effect.

You can have a look at the final project here in Code Pen:

I am currently working on rest of the projects required to complete this certification. You can track my progress here.

--

--