Javascript Making Graphs With Chart.js

Code Snippets Making Graphs With Chart.js


In this code snippet, we’ll learn how to make graphs with Chart.js in Javascript.

Chart.js is a very nice javascript library that allows you to visualize data by making different kinds of graphs/charts/plots. We’ll make a simple line graph in this example.

Note: If you want to know how to make other types of graphs(bar, scatter, pie, …) check out the official documentation here. I was going to cover that in this post but they have everything very well documented with nice code examples.

Let’s see the example below.


In the HTML we need to include the Chart.js library and add a canvas element with an id we’ll reference later from the code.
<!DOCTYPE html>
    <script src=''></script>
        <div id='chartWrapperDiv' style="border: 1px solid black;">
            <canvas id="chart" style="width: 100%;"></canvas>

function loadGraph(){  
  //X Axis data points.
  let xAxis = [ 1, 2 , 3, 4, 5 ,6 , 7, 8, 9, 10, 11, 12 ];
  //Y Axis data points.
  let yAxis = [
  const chartSettings = {
    type: "line",
    data: {
      labels: xAxis,
      datasets: [{ 
      	label: "Red Line",
        data: yAxis[0],
        borderColor: "rgba(255,99,132,1)",
        fill: false
      }, { 
      	label: "Blue Line",
        data: yAxis[1],
        borderColor: "rgba(54, 162, 235, 1)",
        fill: false
      }, { 
     	 	label: "Yellow Line",
        data: yAxis[2],
        borderColor: "rgba(255, 206, 86, 1)",
        fill: false
    options: {
      legend: {
      	position: 'bottom',
      	display: true
      title: {
        display: true,
        text: 'Line Chart'
      scales: {
      	yAxes: [{
        	ticks: {
  //Get canvas.
  let canvas = document.getElementById("chart");
  //Make a new chart.
  let chart = new Chart(canvas, chartSettings);

Resulting output:


Leave a Reply

Your email address will not be published.

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger