An Interest In:
Web News this Week
- April 19, 2024
- April 18, 2024
- April 17, 2024
- April 16, 2024
- April 15, 2024
- April 14, 2024
- April 13, 2024
D3.js tutorial: Build your first bar chart
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, were going to show you how to build your first bar chart using D3.js. Lets get started!
Well cover:
- Project overview
- Initial setup
- Create your dataset
- Set dimensions and margins
- Append SVG element
- Gather and format data
- Add bars
- Next steps
Project overview
Today, were 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:
- Set up the documents head and body
- Set up the CSS
- 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, were 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,amountsFoo, 33Rishab, 12Alexis, 41Tom, 16Courtney, 59Christina, 38Jack, 21Mickey, 25Paul, 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 were going to use for the chart and the margins.
// Set graph margins and dimensionsvar 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 rangesvar 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 + ")")
Gather and format data
Its 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 datad3.csv("amounts.csv").then(function(data) { // Format data.forEach(function(d) { d.amounts = +d.amounts; });
Scale domains
Before we add our bars, lets work through our x and y data to make sure its 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
Its 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:
<!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 dimensionsvar margin = {top: 20, right: 20, bottom: 30, left: 40}, width = 960 - margin.left - margin.right, height = 500 - margin.top - margin.bottom;// Set rangesvar 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 datad3.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:
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. Theres 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 Educatives course D3 Tips and Tricks: Interactive Data Visualization. In this course, youll explore D3.js, starting with simple line graphs and moving into more advanced concepts such as histograms and drawing elements. By the end, youll be able to create awesome data visualizations with D3.
Happy learning!
Continue learning about JavaScript
Original Link: https://dev.to/educative/d3-js-tutorial-build-your-first-bar-chart-4cj0
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To