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...
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
xusingscaleBand(). As we are mapping categories to bands ofwidth, we have usedscaleBand()instead oflinearScale(). We have definedpaddingbetween each band using thepadding()function to separate the bars from each other. - Lines 36-39: We draw the bar graph using the
recttag. At the start, we are selecting therectelement, which will give us null as norectelements are present. Then we are binding data, and as we have an empty selection. Then for each data element, we are appending therecttag using theempty()andappend()methods. - Lines 40-41: We have set the
widthof eachrecttox.bandwidthand theheightof eachrecttoheight - y(d.num_students). - Then, we have set the
xandycoordinates ofrecttogradeandnums_studentrespectively.