Data visualization with D3.js

Creating Bar Chart with D3js

Praditya Adhitama
Dec 2, 2019 · 6 min read

The essence of Bar Chart

A bar chart is one great tool to visualize quantitative data. A bar graph divides quantitative data down by group and represents these amounts of each group by using bars of different lengths, using either the number of individuals in each group (also called the frequency) or the percentage in each group (called the relative frequency) (Deborah J. Rumsey). In the simplest words, the graph shows a comparison between different categories or classes. Visually, the bars (each representing certain class/group) is plotted vertically (bars standing up) or horizontally (bars laying flat from left to right). The horizontal (x) axis represents the categories meanwhile the vertical (y) axis represents value for those categories.

D3.js, a data visualization tool for a web interface

D3 is a handy tool for programmers to provide a graphical illustration of data with the purpose of giving a better understanding of certain topics. Regarding data visualization, the library allows coders to bind arbitrary data to a Document Object Model (DOM), and then apply data-driven transformations to in the form of Scalable Vector Graphics (SVG). Executed with OOP style programming in Javascript environment, D3 also offers a flexible and fully customizable way of manipulating DOM and its style to adjust the needs of the end-user. Built upon Jquery, D3 also inherits the same style and mechanism of conducting a broad array of Html operation.

Creating bar chart components with D3.js

In this writing, we will try to elaborate on the components of a bar chart (or histogram) and how to create each component using D3.js. For this purpose, let us breakdown a bar chart model into few components: setting layout, data entry, axis lines & tickmarks, drawing bars.

// =================================================================const margin = {top: 50, right: 50, bottom: 50, left: 50};
const layer = {width: 600,height:400 };
const layout = d3.select('#chart')
.append('svg')
.style("background-color", "white")
.attr("width", layer.width+margin.right+margin.left)
.attr("height", layer.height+margin.top+margin.bottom)
layout.append("g")
.append("text")
.text("Bar Chart")
.style("stroke-width", "1.5px")
.style("fill", "black")
.style("alignment-baseline", "middle")
.attr("x", margin.left)
.attr("y", 30)
.attr("text-anchor", "left")
.attr("font-family", "Poppins")
.attr("font-size", "20px");
// =================================================================const background = d3.select('#chart')
.append('svg')
.style("background-color", "grey")
.attr("width", layer.width)
.attr("height", layer.height)
.attr("transform", `translate(-${layer.width+margin.right},-${margin.top})`);
This is the SVG result up to this step
// =================================================================const data = [
{team:"Chelsea",trophy: 31},
{team:"Manchester United",trophy: 66},
{team:"Arsenal",trophy: 46},
{team:"Liverpool",trophy: 63},
{team:"Manchester City",trophy: 25}]
const teams = data.map(function(object){
return object.team;// creating array of keys
});
const trophiesNum = data.map(function(object){
return object.trophy;// creating array of values
});
const maxValue = d3.max(trophiesNum);// defining max value
// =================================================================const yScale = d3.scaleLinear() // projecting continuous data into the diagram
.domain([100,0])
.range([0,layer.height]);
const xScale = d3.scaleBand() // projecting discrete data into the diagram
.domain(teams)
.range([0,layer.width])
.paddingInner(0.05);
const barColors = d3.scaleLinear() // projecting continuous data into the diagram
.domain([0,maxValue])
.range(["blue","red"])
// =================================================================const yAxis = d3.axisLeft(yScale);
const xAxis = d3.axisBottom(xScale);
const yCartesian = layout.append("g")
.call(yAxis)
.attr("transform", `translate(${margin.right},${margin.top})`);
const xCartesian = layout.append("g")
.call(xAxis)
.attr("transform", `translate(${margin.right},${layer.height+margin.top})`);
Axis lines and tickmarks added
/ ===========================================================  Drawing the barsconst bars = background
.selectAll("rect")
.data(data) //insert data into bars element
.enter()
.append("g")
bars.append("rect")
.attr("width", xScale.bandwidth())
.attr("height", function(d){
return layer.height - yScale(d.trophy)
})
.attr("x", function (d) {
return xScale(d.team)
})
.attr("y", function(d){
return yScale(d.trophy)
})
.style("fill", function(d){
return barColors(d.trophy)
})

The Startup

Get smarter at building your thing. Join The Startup’s +785K followers.

Sign up for Top 10 Stories

By The Startup

Get smarter at building your thing. Subscribe to receive The Startup's top 10 most read stories — delivered straight into your inbox, once a week. Take a look.

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

Praditya Adhitama

Written by

Fullstack Developer and GIS Enthusiast

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +785K followers.

Praditya Adhitama

Written by

Fullstack Developer and GIS Enthusiast

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +785K followers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store