Line Chart

Learn about line charts and how to create them.

We'll cover the following

Introduction

After setting the stage in the previous lesson, let’s take a look at one important chart, a line chart. A line chart is a chart used to visualize data over time. It is also known as a line graph. The line chart consists of the x-axis, y-axis, and the line, which shows the change in the dependent variable on the y-axis with respect to the independent variable on the x-axis.

Example

Let’s look at an example to learn how to draw a line chart. In the following example, we have data from the hospital that shows the number of patients in different months. Let’s draw a line graph for this data with the help of a line generator and scaleTime() scale which is used when we are dealing with time.

Line chart

Explanation

To know how the above code works, let’s take a look into it.

  • Line 4-9:, We have created an SVG canvas of size (700x700).
  • Line 22-25:, We are updating the data by changing the format of the date from string to JavaScript’s Date format.
  • Then we have defined a time scale xscale with help of the scaleTime() scale. The x-axis represents the time, and that is why we have used a time scale instead of a linear scale.
  • Line 32-35: We have created a chart inside the SVG canvas.
  • tickFormat(d3.timeFormat("%b")) has been used in line 37 to show our date in months on the x-axis.
  • Then, we have drawn the line chart with the help of the line generator and path.