Home/Blog/Programming/D3.js tutorial: Build your first bar chart
Home/Blog/Programming/D3.js tutorial: Build your first bar chart

D3.js tutorial: Build your first bar chart

Erin Schaffer
Jun 18, 2021
4 min read

Become a Software Engineer in Months, Not Years

From your first line of code, to your first day on the job — Educative has you covered. Join 2M+ developers learning in-demand programming skills.

D3.js is a JavaScript library that enables you to create dynamic data visualizations in web browsers. It specializes in visualizing large data sets in an understandable and interactive way. The D3.js library stands out as one of the best data visualization tools for front-end developers because of its core features, such as DOM manipulation, dynamic properties, and animations.

Today, we’re going to show you how to build your first bar chart using D3.js. Let’s get started!

Master data visualization with D3.js

Learn how to create interactive data visualizations in D3 with hands-on practice.

D3 Tips and Tricks: Interactive Data Visualization

Project overview#

Today, we’re going to build a bar chart using D3.js. This is a great project because it allows you to practice your D3.js data visualization skills in a practical way.

Bar charts are a useful and effective way to compare data between different groups. They improve readability, allowing you to easily identify patterns or trends in your data.

D3.js is great for data visualization for many reasons, such as:

  • Visuals: works with HTML, CSS, and SVG so no new tools are required
  • Animations: allows you to animate and modify page elements
  • Supported in all major browsers: works on the web making visuals easy to share and publish
  • Flexible: works well with existing web technologies and can manipulate any part of the DOM
  • Scalable: works well with large sets of data

Initial setup#

There are three things we need to do before creating our bar chart:

  1. Set up the document’s head and body
  2. Set up the CSS
  3. Load the d3.js library

They can all be done with the following code:

<!DOCTYPE html>
<meta charset="utf-8">
<style> /* set the CSS */
.bar { fill: steelblue; }
</style>
<body>
<!-- load the d3.js library -->
<script src="https://d3js.org/d3.v6.min.js"></script>
<script>

In the <style> section of the code, we set the styling for the color of the bars. Placing the style at the beginning of the code is optional, but it is convenient to do early.

Create your dataset#

We need data before we can begin working on our bar chart. For this tutorial, we’re going to work with some sample data from a fictional external CSV file named amounts.csv.

The file consists of a column of names and amounts:

name,amounts
Foo, 33
Rishab, 12
Alexis, 41
Tom, 16
Courtney, 59
Christina, 38
Jack, 21
Mickey, 25
Paul, 30

We will use this data to make a vertical bar chart that stores the values of the amounts.

Set dimensions and margins#

Let’s set the size of the area that we’re going to use for the chart and the margins.

// Set graph margins and dimensions
var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;

Now, we’ll determine the ranges of the x and y domains.

// Set ranges
var x = d3.scaleBand()
.range([0, width])
.padding(0.1);
var y = d3.scaleLinear()
.range([height, 0]);

Append SVG element#

The following code selects the body on the webpage and appends an SVG object to it. The size of the SVG object is determined by the width, height, and margin we set up:

var svg = d3.select("body").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 + ")")

Keep the learning going.#

Learn D3.js fast without scrubbing through videos or documentation. Educative’s text-based courses are easy to skim and feature live coding environments, making learning quick and efficient.

D3 Tips and Tricks: Interactive Data Visualization


Gather and format data#

It’s time to load our data into the body of our script. We will load our CSV file and then loop through it to make sure all data is recognized properly:

// Get data
d3.csv("amounts.csv").then(function(data) {
// Format
data.forEach(function(d) {
d.amounts = +d.amounts;
});

Scale domains#

Before we add our bars, let’s work through our x and y data to make sure it’s scaled to our set domains:

// Scale the range of the data in the domains
x.domain(data.map(function(d) { return d.name; }));
y.domain([0, d3.max(data, function(d) { return d.amounts; })]);

Add bars#

It’s time to add the bars! The code we write will create the bars and associate each of them with a data set.

// Append rectangles for bar chart
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.name); })
.attr("width", x.bandwidth())
.attr("y", function(d) { return y(d.amounts); })
.attr("height", function(d) { return height - y(d.amounts); });

The last thing we need to do is append our axes, and then we can check out the finished result.

// Add x axis
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
// Add y axis
svg.append("g")
.call(d3.axisLeft(y));

This is what our code should look like in its entirety:

bar-chart.html
amounts.csv
<!DOCTYPE html>
<meta charset="utf-8">
<style> /* set the CSS */
.bar { fill: steelblue; }
</style>
<body>
<!-- load the d3.js library -->
<script src="https://d3js.org/d3.v6.min.js"></script>
<script>
// Set graph margins and dimensions
var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
// Set ranges
var x = d3.scaleBand()
.range([0, width])
.padding(0.1);
var y = d3.scaleLinear()
.range([height, 0]);
var svg = d3.select("body").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 + ")");
// Get data
d3.csv("amounts.csv").then(function(data) {
// Format data
data.forEach(function(d) {
d.amounts = +d.amounts;
});
// Scale the range of the data in the domains
x.domain(data.map(function(d) { return d.name; }));
y.domain([0, d3.max(data, function(d) { return d.amounts; })]);
// Append rectangles for bar chart
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.name); })
.attr("width", x.bandwidth())
.attr("y", function(d) { return y(d.amounts); })
.attr("height", function(d) { return height - y(d.amounts); });
// Add x axis
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
// Add y axis
svg.append("g")
.call(d3.axisLeft(y));
});
</script>
</body>

This is our finished bar chart:

widget

Next steps#

Congrats on taking your first steps with D3.js data visualization! Bar charts are a great way to visualize large data sets in an understandable and visually appealing way. There’s still a lot to learn about the D3.js library such as:

  • Tree diagrams
  • Sankey diagrams
  • Mapping
  • And much more

To learn about these concepts and learn more about bar graphs in D3.js, check out Educative’s course D3 Tips and Tricks: Interactive Data Visualization. In this course, you’ll explore D3.js, starting with simple line graphs and moving into more advanced concepts such as histograms and drawing elements. By the end, you’ll be able to create awesome data visualizations with D3.

Happy learning!

Continue learning about JavaScript#


  

Free Resources