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!
We’ll cover:
Master data visualization with D3.js
Learn how to create interactive data visualizations in D3 with hands-on practice.
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:
There are three things we need to do before creating our bar chart:
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.
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 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]);
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 + ")")
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.
// Get data d3.csv("amounts.csv").then(function(data) { // Format data.forEach(function(d) { d.amounts = +d.amounts; });
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; })]);
// 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:
<!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:
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:
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!
Join a community of more than 1.2 million readers. A free, bi-monthly email with a roundup of Educative's top articles and coding tips.