Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • jQuery Tutorial
  • jQuery Selectors
  • jQuery Events
  • jQuery Effects
  • jQuery Traversing
  • jQuery HTML & CSS
  • jQuery AJAX
  • jQuery Properties
  • jQuery Examples
  • jQuery Interview Questions
  • jQuery Plugins
  • jQuery Cheat Sheet
  • jQuery UI
  • jQuery Mobile
  • jQWidgets
  • Easy UI
  • Web Technology
Open In App
Next Article:
Chart.js
Next article icon

JavaScript ChartJS

Last Updated : 03 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Chart.js is an open-source JavaScript library available on GitHub that enables the creation of various types of charts using the HTML5 <canvas> element. Since it relies on the canvas API, a polyfill may be needed to ensure compatibility with older browsers that do not natively support the canvas element.

HTML5 Canvas Element

The HTML5 <canvas> element provides a simple and efficient way to draw graphics using JavaScript. It can be used for a variety of purposes, such as drawing graphs, creating photo compositions, or making both simple and complex animations. One of its key features is its responsiveness, meaning it automatically resizes and redraws the chart when the browser window is resized, ensuring perfect scaling and clarity.

This library supports 8 different types of graphs:

  • Line
  • Bar
  • Doughnut
  • Pie
  • Radar
  • Polar Area
  • Bubble
  • Scatter

Installation:

Latest version of Chart.js can be downloaded from the Github or use a Chart.js CDN.

Steps to create a chart:

Step 1: First include the chart.js in the HTML. html

</p><pre><code class="language-html"><head> 	<script src= "https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.js"> 	</script> 	<link rel="stylesheet" type="text/css" href="style.css"> </head></code></pre><p></p><h3><b><strong>Create canvas:</strong></b><span> </span></h3><p dir="ltr"><span>To create a chart we need to represent the Chart class. In order to do this, we need to pass jQuery instance or 2d context of the canvas of where we want the place or draw the chart.  For example:  </span><gfg-tabs data-run-ide="false" data-mode="light"><gfg-tab slot="tab">html 

<canvas id = ”chart” width=”900” height = “900”> </canvas>

Type of Chart and Data:

Decide what type of chart is required and prepare the data accordingly. Data requires labels, datasets, data values, backgroundColor,borderColor, borderWidth and various other options. For example: javascript

</p><pre><code class="language-javascript">labels:[“CS”, “IT” , “ECE” , “EE”, ”ME”, “BE”], And datasets:      Label: ‘# of students’,     Data : [105,124,78,91,62,56],     backgroundColor :['rgba(255, 99, 132, 0.2)',                 'rgba(54, 162, 235, 0.2)',                 'rgba(255, 206, 86, 0.2)',                 'rgba(75, 192, 192, 0.2)',                 'rgba(153, 102, 255, 0.2)',                 'rgba(255, 159, 64, 0.2)' ],  borderColor: [                 'rgba(255,99,132,1)',                 'rgba(54, 162, 235, 1)',                 'rgba(255, 206, 86, 1)',                 'rgba(75, 192, 192, 1)',                 'rgba(153, 102, 255, 1)',                 'rgba(255, 159, 64, 1)'             ]</code></pre><span>And finally, we should decide the type of chart from a line, bar, radar, pie, doughnut, polar area, bubble and scatter. </span><p></p><h3><b><strong>Create a graph:</strong></b><span> </span></h3><p dir="ltr"><span>After defining what type of graph is to be drawn,  pass the data to that graph that we want to visualize. Below is an example: </span><gfg-tabs data-run-ide="false" data-mode="light"><gfg-tab slot="tab">javascript 

let ctx = document.getElementById("chart"); let myChart = new Chart(ctx, {   type: 'bar',   data: {     Labels: [“CS”, “IT” , “ECE” , “EE”, ”ME”, “BE”],     datasets: [       {        label: ‘# of students’,     data : [105,124,78,91,62,56],     backgroundColor :['rgba(255, 99, 132, 0.2)',                 'rgba(54, 162, 235, 0.2)',                 'rgba(255, 206, 86, 0.2)',                 'rgba(75, 192, 192, 0.2)',                 'rgba(153, 102, 255, 0.2)',                 'rgba(255, 159, 64, 0.2)' ],  borderColor: [                 'rgba(255,99,132,1)',                 'rgba(54, 162, 235, 1)',                 'rgba(255, 206, 86, 1)',                 'rgba(75, 192, 192, 1)',                 'rgba(153, 102, 255, 1)',                 'rgba(255, 159, 64, 1)'             ], borderWidth : 1  }       }     ]

Complete code to create a chart:

html
<!DOCTYPE html> <html>  <head>     <script         src= "https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.js">     </script> </head>  <body>      <canvas id="myChart" width="900" height="400"></canvas>     <script type="text/javascript">          let ctx = document.getElementById("myChart");         let myChart = new Chart(ctx, {             type: 'bar',             data: {                 labels: ["CS", "IT", "ECE", "EE", "ME", "BE"],                 datasets: [                     {                         label: '# of students',                         data: [105, 124, 78, 91, 62, 56],                         backgroundColor: ['rgba(255, 99, 132, 0.2)',                             'rgba(54, 162, 235, 0.2)',                             'rgba(255, 206, 86, 0.2)',                             'rgba(75, 192, 192, 0.2)',                             'rgba(153, 102, 255, 0.2)',                             'rgba(255, 159, 64, 0.2)'                         ],                          borderColor: [                             'rgba(255,99,132,1)',                             'rgba(54, 162, 235, 1)',                             'rgba(255, 206, 86, 1)',                             'rgba(75, 192, 192, 1)',                             'rgba(153, 102, 255, 1)',                             'rgba(255, 159, 64, 1)'                         ],                         borderWidth: 1                     }                 ]             },             options: {                 scales: {                     yAxes: [{                         ticks: {                             beginAtZero: true                         }                     }]                 }             }         });      </script>  </body>  </html> 

Output:



Next Article
Chart.js
author
sarthak_ishu11
Improve
Article Tags :
  • JavaScript
  • JQuery
  • Web Technologies
  • JavaScript-Questions

Similar Reads

  • Chart.js
    Chart.js is an open-source JavaScript library on Github that allows you to draw different types of charts by using the HTML5 canvas element. Since it uses Canvas, you have to include a polyfill to support older browsers. Charts.js Installation GuideWhy to use Chart.js?Whenever we need to add any typ
    9 min read
  • Chart.js Radar Chart
    Chart.js Radar Chart is used to present the multivariate data in a spider-web-like format, which allows us to properly analyze and compare more than one quantitative variable in parallel. Using the Radar chart we can properly display the patterns and relationships among the various categories, as ea
    4 min read
  • Data Analysis with JavaScript
    JavaScript, traditionally known for frontend web development has evolved into the versatile language capable of performing complex data analysis tasks. Leveraging its capabilities for data manipulation, visualization, and integration with the backend systems. JavaScript has become a powerful tool in
    6 min read
  • Chart.js Radial Axes
    Chart.js Radical Axes are designed for radar and polar area chart types, overlaying the chart area rather than positioned on the edges. There is one radical axis which is by default and other visual components are angle lines, grid lines, point labels, and ticks. These visual components provide vari
    5 min read
  • Chart.js Axes
    Chart.js Axes provides the necessary context, labels, and scaling to make the charts more informative so that they can look visually appealing. Axes can be applied on various types of charts like lines, bars, radar, etc. Types of AxesAxes: It is an integral part of Chart.js and it is used to determi
    4 min read
  • Charts.js General
    Chart.js General Accessibility ensures the accessibility rendered on user-provided canvas elements. Users can add accessibility features like ARIA attributes or fallback content within the canvas elements. This ensures that the content of the canvas, and chart information is accessible to all the us
    7 min read
  • Implementation of Graph in JavaScript
    Implementing graphs in JavaScript is crucial for visualizing data structures and relationships. JavaScript provides various ways to create and manage graphs, including adjacency lists, adjacency matrices, and edge lists. This guide will cover the basics of graph implementation in JavaScript, demonst
    6 min read
  • Chart.js Bar Chart
    Chart.js Bar chart is a graph that uses rectangular bars to show data. The length of each bar corresponds to the value it represents, making it easy to compare several groupings quickly. Usually, the vertical axis shows the values' scale, and the horizontal axis denotes categories or labels. Bar cha
    4 min read
  • Chart.js Canvas Resize
    The Chart.js library provides responsive, interactive charts that automatically resize based on the size of their parent container. By default, charts created with Chart.js are responsive and will adjust their dimensions to fit the available space on the page. However, if you need to manually resize
    3 min read
  • Chart.js Labeling Axes
    Chart.js Labeling Axes is used to describe the information in a chart. The Scale Title Configuration allows customization of axis titles, which also includes the options for display, alignment, text, color, and padding. Syntax:const config = { type: 'bar', data:, options: { scales: { y: { title: { d
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences