For enquiries call:

Phone

+1-469-442-0620

Easter Sale-mobile

HomeBlogWeb DevelopmentD3 Bar Chart: Create a Bar Graph Using D3.js in Simple Steps

D3 Bar Chart: Create a Bar Graph Using D3.js in Simple Steps

Published
26th Sep, 2023
Views
view count loader
Read it in
11 Mins
In this article
    D3 Bar Chart: Create a Bar Graph Using D3.js in Simple Steps

    In this article, we will learn about D3.js, its key concepts, and how to create bar graphs using D3.js in simple steps, followed by examples. In our journey to plotting a bar chart, we will also come across various new terms and concepts like getting your dataset ready, format axes, adding labels, and more. So let us get started. 

    D3.js – An Overview 

    D3.js is a JavaScript library that allows you to interact with data. With D3, you can quickly create dynamic data visualizations in the web browser using HTML, CSS, and SVG. D3 is extremely fast, can handle large datasets, and allows for dynamic interactions and animations. As a result of these capabilities, it has emerged as one of the best data visualization tools for front-end developers.  To know more about web development, check out Full Stack Developer classes.  

    To use D3, you can download the zip file from here

    Alternatively, you can link directly to the latest release using the snippet: 

    <script src="https://d3js.org/d3.v7.min.js"></script> 

    Apart from this, you can also integrate D3.js with NodeJS very easily. If you’re not familiar with NodeJS and are looking to get started, check out this Node JS Master Class

    Getting the Dataset 

    You'll need a dataset before you start plotting the D3 bar chart. For simplicity, we will take a fictional dataset of marks obtained by ten students in their final examinations. The data will exist in a CSV file named marksheet.csv that looks like this: 

    name,marks 
    Shiva,98 
    Edward,75 
    Daniel,88 
    Albert,91 
    David,79 
    Alice,99 
    Linca,77 
    Julie,95 
    Swathi,82 
    Maria,94 

    D3 and SVG 

    SVG, or Scalable Vector Graphics, is an XML-based vector graphics format that provides more flexibility and power for designing visualizations. 

    We can create SVGs in two different ways: 

    1. Initialize a SVG container with width and height as below: 

    <svg width="600" height="400"></svg> 

    2. First, create a div container in the HTML code. 

    <div id="svgContainer"></div> 

    Then select the container to inject the svg element using JavaScript. 

    var svg = d3 
    .select("#svgContainer") 
    .append("svg") 
    .attr("width", 600) 
    .attr("height", 400); 

    Setting-up Our Project

    To continue with the tutorial, you will need to set up the project. You’ll be using two files in total: 

    • index.html: In this file, you will place your HTML code. 
    • script.js: This will be the most important file where you will be interacting with D3.js to create bar charts. 

    Additionally, you can create a style.css file where you can put your CSS code. However, we won’t be doing much CSS here to keep the tutorial as simple as possible. 

    Create an index.html file and place the following HTML code in that: 

    <!DOCTYPE html> 
    <html lang="en"> 
    <head> 
    <meta charset="UTF-8" /> 
    <meta http-equiv="X-UA-Compatible" content="IE=edge" /> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0" /> 
    <title>Bar Graph using D3.js</title> 
    </head> 
    <body> 
    <svg width="1000" height="400"></svg> 
    <script src="https://d3js.org/d3.v7.min.js"></script> 
    <script src="script.js"></script> 
    </body> 
    </html> 

    In the body of the above HTML code, we have created an SVG container initialized with a width of 1000 and a height of 400. We have also linked to the D3.js file as discussed above and our custom JavaScript file, which will be empty for the time being.

    D3.js Selections

    One of the most important concepts in D3.js is Selections. Similar to CSS selectors, it helps you select elements on the webpage. In addition to that, you can modify, append, or remove elements.

    With D3.js, you get the following two methods to select elements on the webpage: 

    • select() − It selects only one DOM element by matching the CSS selector. If it matches more than one element, it will select the first one only. 
    • selectAll() − It selects all the DOM elements by matching the CSS selector.

    The selection methods support chaining, which lets you easily apply multiple operations to the same elements. 

    If you want to learn more about CSS selectors and other important things related to Web Development, check out this Web Development Course with certificate that will help you learn basics to advanced topics.  

    How to Set up Margins?

    To make the bar chart look more centered and clear, you can set margins for the SVG.

    var svg = d3.select("svg"), 
    margin = 200, 
    width = svg.attr("width") - margin, 
    height = svg.attr("height") - margin; 

    First of all, the SVG element is selected using the select() method from the D3.js library. After that, we initialized a margin variable with 200. This margin is used to adjust the width and height of the SVG container. Notice that, instead of using values 1000 and 400 for width and height, respectively, we used the svg.attr(“width”) and svg.attr(“height”) so that we need not change these values everywhere in the future. 

    How to Set-up Scales?

    You'll need to adjust the scale for both axes because you'll be working with two. You will be putting the Student Names, which are discrete bands, on the x-axis. As a result, you'll be calling scaleBand() which is used to construct a band scale.

    var xScale = d3.scaleBand().range([0, width]).padding(0.5); 

    The scale function requires a domain and a range where the domain is the input, and the range is the output. The domain can be provided after loading the data from the CSV file. Because we're on the x-axis, the range will be the width of the SVG container. In addition to that, we have provided padding of 0.5 between all the bars. 

    For the y-axis, we will use a linear scale to represent the marks obtained by the students. As we are on the y-axis, the range of this scale will equal the height of the SVG container. 

    var yScale = d3.scaleLinear().range([height, 0]); 

    How to Create a Group Element?

    The <g> SVG element acts as a container for other elements. The transformations applied to this <g> element are applied to its child elements, and its attributes are inherited by its children. To create a <g> element, just append it using any selection as: 

    var g = svg.append("g").attr("transform", "translate(" + 100 + "," + 100 + ")"); 

    In addition to creating the group element, we added a transform attribute to position our graph with some margin. 

    How to Set the Domains?

    As discussed earlier, we’ll need to load our CSV data to set the domain. Let us load the data now: 

    d3.csv("marksheet.csv").then(function (data) { 
    xScale.domain( 
    data.map(function (d) { 
    return d.name; 
    }) 
    ); 
    yScale.domain([ 
    0, 
    d3.max(data, function (d) { 
    return d.marks; 
    }), 
    ]); 
    }); 

    First, the data is loaded using the d3.csv() method. After that, we set the domain of xScale by mapping the name of the students to the x-axis using the data.map() function. Similarly, we set the domain of yScale to 0 to the maximum marks obtained by any student. 

    How to Add and Format Axes?

    Now let us create the two axes and format them as per our requirements. 

    g.append("g") 
    .attr("transform", "translate(0," + height + ")") 
    .call(d3.axisBottom(xScale)) 

    We create another group element so that our x-axis is grouped under one element. We then use the transform attribute to shift our x-axis towards the bottom of the SVG. and insert the x-axis on this group element using .call(d3.axisBottom(x)). 

    Similarly, we can add the y-axis too, but we won’t require any transformation in this case. 

    g.append("g") 
    .call(d3.axisLeft(yScale)) 

    At this point, our bar chart looks like this: 

    How to Add Bars?

    This is the most important step in this tutorial, where we're going to create the bars for the corresponding values and add them to the bar chart. Since this is a vertical bar graph, the width of each bar will remain constant, whereas the height will vary according to the data.

    g.selectAll(".bar") 
    .data(data) 
    .enter() 
    .append("rect") 
    .attr("class", "bar") 
    .attr("x", function (d) { 
    return xScale(d.name); 
    }) 
    .attr("y", function (d) { 
    return yScale(d.marks); 
    }) 
    .attr("width", xScale.bandwidth()) 
    .attr("height", function (d) { 
    return height - yScale(d.marks); 
    }); 

    To create bars with variable heights, we use the SVG rectangle element. We add a bar class to each of the bars, which can be further used to customize the style of the bars. As we have already seen that the xScale and yScale return the corresponding x and y values from the range, we use them to get those values. The width of the bars is calculated using xScale.bandwidth() function. The height of the bar is calculated as height - yScale(d.value), meaning the height of the SVG minus the corresponding y-value of the bar from the y-scale. 

    After adding the bars to the graph, our bar graph looks like this: 

    How to Add Labels?

    At this point, you are almost done with our bar chart creation. But looking at the graph, one won’t be able to say what it represents. To solve this, you can add labels to the bar chart.

    Let us create three labels - one for the x-axis, the second for the y-axis and the third for the bar chart. To create labels, we can append text elements to the SVG.

    For the x-axis, we can append the text element to the group element created for the x-axis: 

    g.append("g") 
    .attr("transform", "translate(0," + height + ")") 
    .call(d3.axisBottom(xScale)) 
    .append("text") 
    .attr("y", height - 140) 
    .attr("x", width - 400) 
    .attr("text-anchor", "end") 
    .attr("stroke", "black") 
    .attr("font-size", "15px") 
    .text("Students"); 

    For the y-axis, we can append the text element to the group element created for the y-axis: 

    g.append("g") 
    .call(d3.axisLeft(yScale)) 
    .append("text") 
    .attr("transform", "rotate(-90)") 
    .attr("x", -80) 
    .attr("y", 25) 
    .attr("dy", "-5.1em") 
    .attr("text-anchor", "end") 
    .attr("stroke", "black") 
    .attr("font-size", "15px") 
    .text("Marks"); 

    For the label of the bar chart, we can append the text element to the svg as: 

    svg 
    .append("text") 
    .attr("transform", "translate(100,0)") 
    .attr("x", 200) 
    .attr("y", 50) 
    .attr("font-size", "20px") 
    .text("Students' Marks in Final Exams"); 

    Final Code and Bar Chart

    Now that we have completed our bar chart, it looks like this: 

    Below is the final JavaScript code after completing the bar chart: 

    var svg = d3.select("svg"), 
    margin = 200, 
    width = svg.attr("width") - margin, 
    height = svg.attr("height") - margin; 
     
    svg 
    .append("text") 
    .attr("transform", "translate(100,0)") 
    .attr("x", 200) 
    .attr("y", 50) 
    .attr("font-size", "20px") 
    .text("Students' Marks in Final Exams"); 
     
    var xScale = d3.scaleBand().range([0, width]).padding(0.5), 
    yScale = d3.scaleLinear().range([height, 0]); 
     
    var g = svg.append("g").attr("transform", "translate(" + 100 + "," + 100 + ")"); 
     
    d3.csv("marksheet.csv").then(function (data) { 
    xScale.domain( 
    data.map(function (d) { 
    return d.name; 
    }) 
    ); 
    yScale.domain([ 
    0, 
    d3.max(data, function (d) { 
    return d.marks; 
    }), 
    ]); 
     
    g.append("g") 
    .attr("transform", "translate(0," + height + ")") 
    .call(d3.axisBottom(xScale)) 
    .append("text") 
    .attr("y", height - 140) 
    .attr("x", width - 400) 
    .attr("text-anchor", "end") 
    .attr("stroke", "black") 
    .attr("font-size", "15px") 
    .text("Students"); 
     
    g.append("g") 
    .call(d3.axisLeft(yScale)) 
    .append("text") 
    .attr("transform", "rotate(-90)") 
    .attr("x", -80) 
    .attr("y", 25) 
    .attr("dy", "-5.1em") 
    .attr("text-anchor", "end") 
    .attr("stroke", "black") 
    .attr("font-size", "15px") 
    .text("Marks"); 
     
    g.selectAll(".bar") 
    .data(data) 
    .enter() 
    .append("rect") 
    .attr("class", "bar") 
    .attr("x", function (d) { 
    return xScale(d.name); 
    }) 
    .attr("y", function (d) { 
    return yScale(d.marks); 
    }) 
    .attr("width", xScale.bandwidth()) 
    .attr("height", function (d) { 
    return height - yScale(d.marks); 
    }); 
    }); 

    Are you ready to unlock the power of Python? Join our cutting-edge course for Python developers and take your coding skills to new heights. Don't miss out on this unique opportunity to become a Python pro!

    Conclusion

    Congratulations on creating your first bar chart using D3.js. You can play around the code and add various customizations to it as per your needs. Similar to vertical bar charts, you can create a horizontal bar chart, a grouped bar chart, or a stacked bar chart - the choices are endless. 

    D3.js is a vast library to work with DOM. In this tutorial, we just explored a fragment of it. There’s still a lot to learn about it. Hope the tutorial gave you a good kick start towards your journey of working with D3.js. 

    Now that you’ve learned about a new library, you might love to check out this KnowledgeHut Node JS Master Class, where you will get hands-on experience in building everything from command-line tools to web servers and more. 

    Frequently Asked Questions (FAQs)

    1What is the use of D3.js?

    D3 is a JavaScript library for creating data visualizations by binding the data and graphical elements to the Document Object Model. 

    2How can I use D3.js?

    To use D3.js, you need to install it either by downloading the source zip file from here or using the HTML script tag to import the library. 

    3Is it easy to create a bar graph with D3?

    At first, it may look intimidating but it’s not difficult at all. You need to follow the steps sequentially, and you will be able to create the bar graph for your data in a few minutes. 

    4What is D3.js?

    D3.js is a JavaScript library that allows you to interact with data. With D3, you can quickly create dynamic data visualizations in the web browser using HTML, CSS, and SVG. D3 is extremely fast, can handle large datasets, and allows for dynamic interactions and animations. 

    5What is range and domain in D3?

    The scale function requires input and maps it to output. The input given to the scale function is called the domain and the output provided by it is called range. 

    Profile

    Ashutosh Krishna

    Author

    Ashutosh is an Application Developer at Thoughtworks. Apart from his love for Backend Development and DevOps, he has a keen interest in writing technical blogs and articles. 

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon