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.
Explanation
Let’s go into details about the above code to better understand how it works.
- Line 19-22: We have defined
x
usingscaleBand()
. As we are mapping categories to bands ofwidth
, we have usedscaleBand()
instead oflinearScale()
. We have definedpadding
between each band using thepadding()
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 therect
element, which will give us null as norect
elements are present. Then we are binding data, and as we have an empty selection. Then for each data element, we are appending therect
tag using theempty()
andappend()
methods. - Line 39-40: We have set the
width
of eachrect
tox.bandwidth
and theheight
of eachrect
toheight - y(d.num_students)
. - Then, we have set the
x
andy
coordinates ofrect
tograde
andnums_student
respectively.