Chart.js - Syntax



To create a chart using chart.js library, we need to know the following details regarding the chart −

  • Position of the chart
  • Type of graph
  • Chart configuration
  • Responsiveness

Let's take a simple chart.js example and understand how you can supply this data in your code −

Example

In this example, we will create a basic chart using the chart.js library −

<!DOCTYPE>
<html>
<head>
   <meta charset- "UTF-8" />
   <meta name="viewport" content="width=device-width, initial-scale=1" />
   <title>chart.js</title>
</head>
<body>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.1.1/chart.min.js"></script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.1.1/helpers.esm.min.js"></script>
   <canvas id="graph" aria - label="chart" height="350" width="580"></canvas>
   <script>
      var chrt = document.getElementById("graph");
      var graph = new Chart(chrt, {
         type: 'bar',
         data: {
            labels: ["HTML", "CSS", "JAVASCRIPT", "CHART.JS", "JQUERY", "BOOTSTRP"],
            datasets: [{
               label: "online tutorial subjects",
               data: [9, 8, 10, 7, 6, 12],
            }],
         },
         options: {
            responsive: true,
         },
      });
   </script>
</body>
</html>

Use the "Edit and Run" option and run this code to see the kind of chart it produces.

Description

Given below is the description of various object used in chart.js syntax −

  • Canvas − It help us to select a position of the graph or chart. You can provide the height and width of your chart.

  • Chart − As name implies, this object will create a chart or graph using the canvas id.

  • Type − It provides various types of the graph and charts such as Pie chart, Bar chart, Bubble chart, etc. You can choose the types of graphs as per your requirement.

  • Labels − The labels assign heading to different elements of the graph or chart. For example, HTML, CSS, JAVASCRIPT, etc. are the labels in above given example.

  • Label − Like Labels, object label assigns heading to the graph or chart itself.

  • Data − The Data object provides values of the graph elements. For example, 9, 8, 10, 7, 12 etc. is the data assigned for various labels in the above given example.

  • Options − The options object adds are the features like animation, integration, responsive to our graph or chart.

Advertisements