The Wayback Machine - https://web.archive.org/web/20240912111522/https://www.geeksforgeeks.org/javascript-chart-js/
Open In App

JavaScript | Chart.js

Last Updated : 19 Feb, 2019
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

So, what is HTML5 Canvas Element ?

The HTML5 element gives an easy and powerful way to draw graphics using JavaScript. It can be used to draw graphs, make photo compositions or do simple (and not so simple) animations.
It is responsive in nature that means it redraws chart on resizing of window for perfect scale granularity.

This library supports 8 different types of graphs :

  1. Line
  2. Bar
  3. Doughnut
  4. Pie
  5. Radar
  6. Polar Area
  7. Bubble
  8. Scatter

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

    Steps to create a chart:

  1. First include the chart.js in the HTML.




    <head>
    <script src=
    </script>
    <link rel="stylesheet" type="text/css" href="style.css">
    </head>

    
    

  2. Create canvas: 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:




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

    
    

  3. 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:




    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)'
                ]

    
    

    And finally, we should decide the type of chart from a line, bar, radar, pie, doughnut, polar area, bubble and scatter.

  4. Create a graph: 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:




    var ctx = document.getElementById("chart");
    var 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:




<!DOCTYPE html>
<html>
<head>
<script 
</script>
</head>
<body>
  
<canvas id="myChart" width="900" height="400"></canvas>
<script type="text/javascript">
  
var ctx = document.getElementById("myChart");
var 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:



Similar Reads

How to Set Chart Title and Name of X Axis and Y Axis for a Chart in Chart.js ?
In this article, we will learn how to set the title, the name of the x-axis, and the name of the y-axis for a chart using the ChartJS CDN library. Approach:In the HTML template, use the &lt;canvas&gt; tag to show the line graph.In the script section of the code, instantiate the ChartJS object by setting the type, data, and options properties of the
3 min read
Chart.js Mixed Chart Types
Chart.js mixed Chart Type is a single graphical representation in which multiple chart types are combined. Examples are line, bar, radar, and doughnut in a single chart. It will help to differentiate data with proper visualization. In this article, we will learn about the Mixed Chart Types in Chart.js. NOTE: When creating a mixed chart, we specify
3 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 charts are frequently used for showing and analyzing
4 min read
Chart.js Line Chart
Chart.js line chart is a visual representation of data points connected by straight lines, depicting trends or patterns in a dataset over time or categories. Syntax: let myBarChart = new Chart(ctx, { type: 'line', data: data, options: options });Dataset PropertiesborderCapStyle - Cap style of the linebackgroundColor - it is used to fill the line.bo
4 min read
How to Limit the Number of Labels on a Line Chart in Chart.js ?
In this article, we will see two different approaches to control and limit the number of labels on the Line Chart in Chart.JS. We will see the practical implementation of these approaches with user interactive examples and their outputs. Table of Content Approach 1: Using maxTicksLimit PropertyApproach 2: Using CallbackChart.js CDN Link&lt;script s
4 min read
How to Set Different Colors for Each Bar for a Bar Chart in Chart.js ?
In the Bar Chart, for unique identification, we can assign unique colors to each Bar. In this article, we will see how to set different colors for each bar for a bar chart in chart.js. We can assign unique colors to the Bar using various approaches. Table of Content Approach 1: Using randomly generated colors ArrayApproach 2: Using FunctionCDN Link
2 min read
How to Create a Horizontal Scrolling Chart.js Line Chart with a Locked Y Axis ?
We will learn how to create a horizontal scrolling Chart.js line chart with a locked y-axis using the ChartJS CDN library. ApproachIn the HTML template, use two &lt;canvas&gt; tags: one to show the y-axis which should be locked in place, and the other to show the line chart itself.Create one &lt;div&gt; tag to wrap the first &lt;canvas&gt; tag (the
4 min read
Chart.js Scatter Chart
Chart.js Scatter Chart is a data visualization concept that allows users to represent and analyze the relationship between two numerical variables. Scatter charts use points or markers to represent the data points for showing the patterns, trends, and correlations. Mainly, the scatter chart can be used for exploring the distribution of data points
4 min read
Chart.js Bubble Chart
Chart.js Bubble Chart is used to display the three-dimensional data or 3D data. This chart uses the horizontal and vertical axes to position the bubbles based on the first two dimensions, in which the size of each bubble describes the 3rd dimension. Syntax:new Chart($("#ID"), { type: 'bubble', data: { ... }, options: { ... }});Dataset PropertiesThe
4 min read
Chart.js Area Chart
In this article, we will learn to implement an Area Chart using the Chart JS CDN library. A Chart.js Area Chart is the type of chart that is mainly used to represent the data points over the continuous axis by filling the area or portion within the data line and the axis by making it a colored portion. The Area Chart is mainly used to display the m
4 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 each axis links to a specific data dimension. Syntax
4 min read
How to Vary the Thickness of Doughnut Chart in Chart.js ?
Doughnut charts are widely used for representing data in a circular format that allows users to compare the proportions of different categories. We can use the cutout percentage property to accomplish this task. ChartJS CDN Link:To use Chart.js you have to include the CDN link in your HTML. &lt;script src="https://cdn.jsdelivr.net/npm/chart.js"&gt;
2 min read
Chart.js Polar Area Chart
Chart.js Polar Area Chart is the type of chart that represents the data in a circular shape format which is quite similar to the pie chart. Like the pie chart, each segment in the Polar Area chart has the same angle with the radius of the segment different from each other. This Polar Area chart is mainly used to provide a visual representation of c
4 min read
How to Set Height and Width of a Chart in Chart.js ?
Chart.js is a popular JavaScript library that allows developers to create interactive and visually appealing charts for web applications. One of the key aspects of chart customization is controlling its dimensions. In this article, we'll explore how to set the height and width of a Chart.js chart. Chart.js CDN link &lt;script src="https://cdnjs.clo
4 min read
How to Add Text Inside the Doughnut Chart Using Chart.js ?
In Chart.JS, we have a doughnut chart to represent the data in slice forms for a more visual and attractive appearance. In the Doughnut Chart, we can place a custom text inside the doughnut chart to make the chart more informative and also help the readers understand the purpose or data doughnut chart. In this article, we will see two different app
4 min read
Stacked Bar Chart with Groups in Chart.JS
Stacked Bar Charts are a powerful way to visualize the cumulative value of different datasets across multiple categories, providing a clear comparison of data within each group. In Chart.js, you can create stacked bar charts by grouping and stacking datasets, making it easier to analyze the total and individual contributions of each category. Chart
3 min read
How to Converte Chart.js Canvas Chart to Image using .toDataUrl() Results in Blank Image?
In Chart.js, we can convert the canvas chart into an image using the .toDataURL() method, which generates a base64-encoded data URL representing the chart. This allows us to save or display the chart as an image. These are the following approaches: Table of Content Basic Conversion to ImageAdvanced Conversion with Custom Image StylingChartJS CDN Li
4 min read
Chart.js Chart Types
In this article, we will explore some of the key chart types provided by Chart.js, covering their descriptions, syntax, examples, and outputs. Chart.js offers a diverse set of chart types, each designed to convey specific types of data effectively. It also helps to see the computed data at a glance, in order to analyze &amp; make the required decis
4 min read
Chart.js Failed To Create Chart: can't acquire context from the given item
Chart.js is a popular JavaScript library used for creating interactive and visually appealing charts on the web. One common error developers encounter when using Chart.js is: "Failed to create chart: can't acquire context from the given item." This error typically occurs when Chart.js fails to access the rendering context of the &lt;canvas&gt; elem
4 min read
Create a chart from JSON data using Fetch GET request (Fetch API) in JavaScript
In this article, we are going to create a simple chart by fetching JSON Data using Fetch() method of Fetch API. The Fetch API allows us to conduct HTTP requests in a simpler way. The fetch() method: The fetch method fetches a resource thereby returning a promise which is fulfilled once the response is available. Syntax: const response = fetch(resou
3 min read
Angular PrimeNG Combo Chart Component
Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will see the Angular PrimeNG Combo Chart Component. The Combo Chart Component provides various kinds of charts that can be combine
3 min read
How to create line chart using react bootstrap ?
Line charts are used to represent the relation between two data X and Y on a different axis. One of the axes of the plot represents the specific categories being compared, while the other axis represents the measured values corresponding to those categories. Creating React Application And Installing Module: Step 1: Create a React application using
2 min read
How to Create Bar Chart using React Bootstrap ?
A bar plot or bar chart is a graph that represents the category of data with rectangular bars with lengths and heights that is proportional to the values which they represent. The bar plots can be plotted horizontally or vertically. A bar chart describes the comparisons between the discrete categories. One of the axes of the plot represents the spe
2 min read
How to Create Radar Chart using React Bootstrap ?
The radar chart is a chart or plot that consists of a sequence of equiangular spokes, called radii, with each spoke representing one of the variables. A radar chart is basically a graphical method of displaying data in the form of a two-dimensional chart of three or more quantitative variables that are represented on the axes starting from the same
2 min read
React Suite Chart Loading State
React Suite Charts is a popular front-end library with a set of React components that are used to provide a set of charts based on rsuite and echarts. The loading state is important which denotes whether the graph is in the loading state or not. We can use the following approach in ReactJS to use the loading state. Here we have used BarChart to dem
2 min read
How to create scatter chart in React Bootstrap ?
Scatter plots are used to observe relationship between variables and uses dots to represent the relationship between them. Scatter plots are widely used to represent relation among variables and how a change in one affects the other. Creating React Application And Installing Module: Step 1: Create a React application using the following command. np
2 min read
How to create doughnut chart in React Bootstrap ?
Doughnut charts are the modified version of Pie Charts with the area of center cut out. A doughnut is more concerned about the use of area of arcs to represent the information in the most effective manner instead of Pie chart which is more focused on comparing the proportion area between the slices. Doughnut charts are more efficient in terms of sp
2 min read
How to create chart using bootstrap ?
A chart in Bootstrap is a graphical representation for data visualization, in which the data is represented by symbols. The various types of charts like bar charts, line charts, pie charts, donut charts, etc are created with the help of Bootstrap. In other words, we can say that chart is a type of diagram or graph, that organizes and represents a s
3 min read
How to create a Line Chart With CSS ?
The Chart is a pictorial or graphical representation of the data visualization, based on certain conditions There are various types of charts available such as Bar Charts, Line Charts, Pie Charts, etc, that are used to represent important data. In this article, we will see how to create the Line chart using HTML &amp; CSS. A Line Chart is a chart t
6 min read
Angular PrimeNG Line Chart Line Styles
Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will see the Line Chart Line Styles in Angular PrimeNG. A line chart or line graph is a type of chart that displays information as
3 min read