Search⌘ K
AI Features

Bar Chart

Explore how to build bar charts using D3.js by understanding scaleBand for categorical axes, binding data to SVG rect elements, and setting their position and size. This lesson helps you visualize comparisons among categories with accurate axes and padding for clarity.

We'll cover the following...

Introduction

In this lesson, let’s dive into the last graph in this course, the bar chart. A bar chart or bar graph is used to represent categorical data with rectangular bars of varying heights representing the values of the respective categories.

A bar graph shows comparisons among categorical data. The x-axis of the chart shows the specific categories being compared, and the y-axis represents the values associated with each category.

Example

Let’s look at an example where we want to show the number of students that belong to different categories of grades.

Explanation

Let’s go into details about the above code to better understand how it works.

  • Lines 20-23: We have defined x using scaleBand(). As we are mapping categories to bands of width, we have used scaleBand() instead of linearScale(). We have defined padding between each band using the padding() function to separate the bars from each other.
  • Lines 36-39: We draw the bar graph using the rect tag. At the start, we are selecting the rect element, which will give us null as no rect elements are present. Then we are binding data, and as we have an empty selection. Then for each data element, we are appending the rect tag using the empty() and append() methods.
  • Lines 40-41: We have set the width of each rect to x.bandwidth and the height of each rect to height - y(d.num_students).
  • Then, we have set the x and y coordinates of rect to grade and nums_student respectively.