Chart.js JavaScript Tutorial

What is Chart.js

Chart.js is known for its simplicity and ease of use. It creates responsive charts out-of-the-box and will look good on most devices natively. Chart.js uses HML5 canvas elements, which is more scalable than an SVG rendering approach. it is well documented with good community support. Chart.js isn't as highly customizable as other options on the market, which can be a negative for those looking to fully customize their end experience.

What is Javascript?

Javascript is the base language by which people build charts and websites for the web. There are many additional frameworks that are built on top of Javascript. Learning Javascript is an absolute must for modern web development, particularly when it comes to using a charting library.

Chart.js JavaScript Code Example

This example demonstrates how to create a simple line chart using the Chart.js library, a popular, flexible, and easy-to-use JavaScript charting library. We will plot a line chart representing sales data over a week.

HTML Setup

First, include the Chart.js library in your HTML file. This can be done via a CDN (Content Delivery Network) link.

<!DOCTYPE html>

<html>

<head>

   <title>Chart.js Example</title>

   <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

</head>

<body>

   <canvas id="myChart" width="400" height="400"></canvas>

   <script src="path_to_your_script.js"></script>

</body>

</html>

JavaScript: Creating the Line Chart

In your JavaScript file (referenced as "path_to_your_script.js" in the HTML), you'll set up the data and configuration for the chart.

// Select the canvas element from your HTML

var ctx = document.getElementById('myChart').getContext('2d');

// Data for the chart

var data = {

   labels: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],

   datasets: [{

       label: 'Weekly Sales',

       backgroundColor: 'rgb(255, 99, 132)',

       borderColor: 'rgb(255, 99, 132)',

       data: [50, 60, 70, 80, 90, 100, 110],

       fill: false,

   }]

};

// Configuration options

var options = {

   scales: {

       yAxes: [{

           ticks: {

               beginAtZero:true

           }

       }]

   }

};

// Creating the chart

var myChart = new Chart(ctx, {

   type: 'line',

   data: data,

   options: options

});

This code initializes a new Chart instance, specifying the type of chart as 'line'. It uses the data and configuration options defined above to render a line chart inside the canvas element with id 'myChart'.

Through Chart.js, you can create various types of charts by changing the 'type' property and adjusting the data and options to fit your specific needs.

ABOUT EXPLO

Explo, the publishers of Graphs & Trends, is an embedded analytics company. With Explo’s Dashboard and Report Builder product, you can a premium analytics experience for your users with minimal engineering bandwidth.
Learn more about Explo →