Open In App

How to Implement Line Chart using ChartJS ?

Last Updated : 05 Aug, 2024
Comments
Improve
Suggest changes
3 Likes
Like
Report

In this article, we will learn to implement a line chart using the Chart JS CDN library.

A line chart is a chart that helps in plotting data points on a line. It is used to show data that is in some current trend or some change in information with time or the comparison of two data sets. It connects many points using a line or segment. It helps in analyzing or predicting future markets and opportunities. 

Approach:

  • In the HTML design, use the <canvas> tag for showing the line graph.
  • In the script part of the code, instantiate the ChartJS object by setting the type, data, and options properties of the library.
  • Set other required options inside each property like datasets, label, borderColor,fill, scales, and others as per the need of the programmer.

CDN link:

<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js”></script> <script src=”https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.1.2/chart.umd.js”></script>

Syntax:

new Chart($("#ID"), {
type: 'line',
data: { ... },
options: { ... }
});

Example 1: The following code shows a simple example of a line chart with months of the year on the horizontal axis and a number dataset on the vertical axis.

Output:


Example 2: The following code shows another example of a line chart. Each segment is styled using some of the helper functions. Gaps in the data ('skipped') are set to dashed lines and segments with values going 'down' are set to a different color as shown below in the output picture.

Output:


Next Article

Similar Reads