Bar Chart

Get a brief introduction to bar charts and learn how to draw a bar chart in D3.js.

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.

Bar chart

Explanation

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

  • Line 19-22: 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.
  • Line 35-38: 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.
  • Line 39-40: 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.