Chart.js: A comprehensive guide to Data Visualisation

INTRODUCTION

Chart.js is a popular open source JavaScript library for Data-Visualization and powered by HTML5 as its foundational technology. Providing robust customization options and an easy to use API, it is often used to build dashboards, reports, or any interactive application. With over 2 million monthly npm downloads, Chart.js is actively developed by the community, receiving bi-monthly minor revisions and major changes every couple of years, providing a balance between adding new features and keeping up with them.

PREREQUISITES

To understand, learn and setuo Chart.js, you need the following:

  1. To start off basic Web development knowledge is necessary for:
  • HTML
  • CSS
  • JavaScript
  1. Understanding fundamentals of JavaScript like variables, data structures, functions and objects.

  2. Understanding mordern features of JavaScript like const, let, arrow functions, etc. will help to improve and optimize your syntax.

  3. Chart.js uses HTML5 Canvas for rendering its charts, familiarity with the Canvas API is optional although very helpful.

INSTALLATION & SETUP

Step-1: Setting up JavaScript

To use JavaScript in web apps, do the following:

  • Create a HTML file.
  • Add a <Script> tag to include JavaScript.
  • Now, create a script.js file located in the same folder as the HTML file and add JavaScript code in it.

Alternatively, you can also install and setup JavaScript and run using Node.js. Using Node.js will allow Javascript to run natively without a browser and enables Server-side Scripting. Follow the steps below to install JavaScript using Node.js:

  1. Install Node.js, this is equipped with NPM (Node Package Manager) and Node.js (JavaScript runtime).

Open terminal and run the following command to verify installation:

  • To check Node.js Version: node -v
  • To check NPM Version: npm -v
  1. Install a code editor like VS Code or use sublime text, notepad ++, etc.

  2. Running JavaScript in Node.js

  • Open your terminal and type node and press enter, this opens Node.js REPL.

  • Copy and paste the following command:

  • console.log(“Hello, World!”);

  • The code above will print “Hello World!”.

Step-2: Download & include Chart.js

To utilize chart.js in your project. There are 3 main ways to achieve the same:

1) CDN (Content Delivery Network)

It is a quick and easy method to include Chart.js. For simple webpages, use the following code snippet in your HTML file to include Chart.js from a CDN:

  • <script src=“https://cdn.jsdelivr.net/npm/chart.js”></script>

  • This method works in any browser, always uses the latest revision of chart.js and no need to download files.

2) Install through NPM (Node Package Manager)

For developers using Node.js & Bundlers to build complex web apps, install Chart.js using the following:

  1. Run the following command:
  • npm install chart.js
  1. Then, import chart.js in your JavaScript file using the following command:
  • import Chart from ‘chart.js/auto’;

  • This method is suitable for larger projects and works with modern frameworks.

3) Install Chart.js manually

If one needs to run Chart.js without an internet connection then doenload it manually. Follow these steps:

  1. Download Chart.js from the official site of Chart.js.

  2. Extract its files and place Chart.min.js inside the projects folder.

  3. Include the following code snippst in your HTML:

  • <script src=“js/Chart.min.js”></script>

  • This method works offline and allows the version of chart.js to be controlled.

KEY FEATURES AND EXPLANATION

  1. Multiple chart types can be produced:
  • Line Chart
  • Bar Chart
  • Radar Chart
  • Doughnut & Pie
  • Polar Area Chart
  • Bubble Chart
  • Scatter Chart
  1. Animations and transitions are supported for the above mentioned charts while loading or updating. Animation speed and effect types can also be customised.
  • A sample code snippet is given below which uses the following features:

  • duration: 2000 -> Runs animation for 2s.
  • easing: ‘easeInOutBounce’ -> Gives a bouncy effect while appearing.
  • delay: 500 -> Adds 0.5s delay before start.
  • loop: false -> Animation doesn’t loop, runs for a single time
  1. Interactive and responsive
  • Based on screen size, charts are automatically resized.
  1. Customisation & Styling
  • Customise color, font, gridlines and tooltips, legends and backgrounds by using gradients, images or pattern.
  1. Additional features
  • Charts update dynamically with new data without the page, useful for real-time data visualisation.
  • Uses simple JSON based data structure
  • It’s lightweight, only ~60 KB in size.
  • Uses HTML5 Canvas for efficient rendering.

CODE EXAMPLES

  • Below are some code snippets which goes over the features of chart.js

1. Lets start off with building a line graph

  1. HTML Structure and Chart.js Import

  • Image above defines the document structure.

  • Canvas Element: <canvas id=“myLineChart”></canvas> acts as the drawing area for the chart.

  • Chart.js Import: The script loads Chart.js from CDN, enabling chart.js.

  1. JavaScript – Selecting the Canvas and Initializing the Chart

The changes in the above image are given below

  • Selecting the Canvas → Document.getElementById(‘myLineChart’).getContext(‘2d’); gets the 2D context for drawing.

  • Creating a Chart Object → New Chart(ctx, { … }) initializes a line chart.

  • labels → Defines X-axis values (Months).

  • datasets → Contains Monthly Sales data points.

  • borderColor & backgroundColor → Define the line and fill colors.

  • fill: true → Fills the area under the line.

  • tension: 0.3 → Smooths the line curves.

  1. Configuring Chart Options

  • Responsive Behavior: responsive → True ensures the chart adjusts dynamically to screen size.
  • Y-Axis Settings: beginAtZero → True ensures the Y-axis starts from zero.
  1. Final Line Graph

Summary for the above output:

  • HTML Setup & Chart.js Import → Defines the page structure and loads Chart.js.
  • JavaScript – Chart Creation → Selects the canvas, defines data points, and styles the chart.
  • Chart Configuration → Enables responsiveness and ensures proper Y-axis scaling.

2. Now, lets look into building a bar chart

  1. Bar Graph JavaScript

  • type: ‘bar’ → Specifies that this is a bar chart.
  • labels → Defines the X-axis categories (months).
  • label → Describes the dataset.
  • data → Represents sales figures.
  • backgroundColor → Defines the bar fill color with transparency.
  • borderColor → Defines the bar outline color.
  • borderWidth → Sets the thickness of the bar border.
  1. Bar graph

3. Lets build a Scatter plot

  1. Scatter plot JavaScript

  • document.getElementById(‘myScatterChart’).getContext(‘2d’) gets the 2D drawing context for the scatter plot.
  • type: ‘scatter’ → Specifies that this is a scatter plot.
  • label → “Data Points” (description of the dataset).
  • data → An array of { x, y } values representing scatter points.
  • backgroundColor → Sets the color of the points.
  • borderColor → Defines the border color of points.
  • pointRadius → Sets the size of the points.
  1. Scatter Plot

4. Lastly, lets finish off with a Radar Plot

  1. JavaScript code

  • document.getElementById(‘myRadarChart’).getContext(‘2d’) gets the 2D drawing context for Chart.js.

  • type: ‘radar’ → Specifies that this is a radar chart.

  • labels → Defines categories (Speed, Strength, Agility, Stamina, Skill).

  • label: “Athlete Performance” → describes the dataset.

  • data: [80, 90, 75, 85, 95] → These are the performance scores.

  • backgroundColor: Light blue filled area.

  • borderColor: Darker blue outline of the radar.

  • borderWidth: 2 → makes the outline more visible.

  1. Radar Plot

USE CASES

The usage of chart.js is prevalent in various sectors due to its efficiency and customisation options. Below are some of the practical use cases of it highlighting the various strengths of chart.js:

1) IoT Sensor Data on Low-End Hardware

High efficiency of Chart.js makes it perfect for low-end devices. Developers use this tool to monitor data from sensors in real-time like temperature or humidity in devices like Raspberry Pi. This efficiency enables real-time rendering with smooth animations and without any lag even on low-end devices.

2) Interactive Business Dashboards

Used for Displaying Key Performance Indicators (KPIs) such as sales, revenue, stock market visualisation or traffic. It’s responsiveness and interactivity enables dynamic and clickable charts that adapt to different screen sizes. Real-time and interactive visuals help decision makers to quickly grasp trends.

3) Educational Platforms for Student Performance

Educational tools require that data be presented in a clear and well-suited format. Chart.js provides extensive customisation options, enabling educators to create chart best suited for the use case and align with the needs of the organisation. It’s ease of usage and integration is also very helpful, making it a popular choice for online learning platforms to track various performance parameters.

CONCLUSION

This free JavaScript library turns datasets into visual stories using line graphs, bar charts, pies, and more – all fully customizable and mobile-ready. Perfect for dashboards, reports, or analytics tools, it’s like having a versatile toolkit that works whether you’re a coding newbie or a seasoned pro.

REFERENCES & FURTHER READINGS

  • Chart.js Official Documentation → https://www.chartjs.org/docs/latest/

  • Chart.js GitHub Repository → https://github.com/chartjs/Chart.js

  • Chart.js Getting Started Guide → https://www.chartjs.org/docs/latest/getting-started/

  • Chart.js Customization Guide → https://www.chartjs.org/docs/latest/configuration/

  • Using Chart.js with React → https://react-chartjs-2.js.org/