How to Draw A Chart With Chart.js?

14 minutes read

To draw a chart with chart.js, you will need to follow these steps:

  1. First, include the chart.js library in your HTML file. You can download it from the official website, or include it from a CDN (Content Delivery Network) by adding the following script tag in the head of your HTML file:
1
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>


  1. Next, create a canvas element in your HTML file where you want to display the chart. Give it an id to easily select it later.
1
<canvas id="myChart"></canvas>


  1. In your JavaScript code, select the canvas element using its id, and create a new instance of the Chart object, passing the canvas element and chart configuration as parameters. Here's an example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
var ctx = document.getElementById('myChart').getContext('2d');

var chart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            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: {
            y: {
                beginAtZero: true
            }
        }
    }
});


  1. Customize the chart configuration according to your requirements. In the example above, we created a bar chart with some dummy data. You can modify the chart type, labels, data, colors, and other options as needed.
  2. Finally, you should see the chart rendered on the canvas element specified, based on the provided configuration. You can further enhance your chart using additional options and features provided by chart.js.


That's it! You have successfully drawn a chart using chart.js. Remember to refer to the chart.js documentation for more detailed instructions and advanced usage.

Best JavaScript Books to Read in 2024

1
JavaScript: The Definitive Guide: Master the World's Most-Used Programming Language

Rating is 5 out of 5

JavaScript: The Definitive Guide: Master the World's Most-Used Programming Language

2
Web Design with HTML, CSS, JavaScript and jQuery Set

Rating is 4.9 out of 5

Web Design with HTML, CSS, JavaScript and jQuery Set

3
JavaScript and jQuery: Interactive Front-End Web Development

Rating is 4.8 out of 5

JavaScript and jQuery: Interactive Front-End Web Development

  • JavaScript Jquery
  • Introduces core programming concepts in JavaScript and jQuery
  • Uses clear descriptions, inspiring examples, and easy-to-follow diagrams
4
JavaScript: The Comprehensive Guide to Learning Professional JavaScript Programming (The Rheinwerk Computing)

Rating is 4.7 out of 5

JavaScript: The Comprehensive Guide to Learning Professional JavaScript Programming (The Rheinwerk Computing)

5
JavaScript from Beginner to Professional: Learn JavaScript quickly by building fun, interactive, and dynamic web apps, games, and pages

Rating is 4.6 out of 5

JavaScript from Beginner to Professional: Learn JavaScript quickly by building fun, interactive, and dynamic web apps, games, and pages

6
JavaScript All-in-One For Dummies

Rating is 4.5 out of 5

JavaScript All-in-One For Dummies

7
Learn JavaScript Quickly: A Complete Beginner’s Guide to Learning JavaScript, Even If You’re New to Programming (Crash Course With Hands-On Project)

Rating is 4.4 out of 5

Learn JavaScript Quickly: A Complete Beginner’s Guide to Learning JavaScript, Even If You’re New to Programming (Crash Course With Hands-On Project)

8
Eloquent JavaScript, 3rd Edition: A Modern Introduction to Programming

Rating is 4.3 out of 5

Eloquent JavaScript, 3rd Edition: A Modern Introduction to Programming

  • It can be a gift option
  • Comes with secure packaging
  • It is made up of premium quality material.
9
Head First JavaScript Programming: A Brain-Friendly Guide

Rating is 4.2 out of 5

Head First JavaScript Programming: A Brain-Friendly Guide

10
Learning JavaScript: JavaScript Essentials for Modern Application Development

Rating is 4.1 out of 5

Learning JavaScript: JavaScript Essentials for Modern Application Development

11
Learning PHP, MySQL & JavaScript: A Step-by-Step Guide to Creating Dynamic Websites (Learning PHP, MYSQL, Javascript, CSS & HTML5)

Rating is 4 out of 5

Learning PHP, MySQL & JavaScript: A Step-by-Step Guide to Creating Dynamic Websites (Learning PHP, MYSQL, Javascript, CSS & HTML5)

12
Learning JavaScript Design Patterns: A JavaScript and React Developer's Guide

Rating is 3.9 out of 5

Learning JavaScript Design Patterns: A JavaScript and React Developer's Guide

13
Professional JavaScript for Web Developers

Rating is 3.8 out of 5

Professional JavaScript for Web Developers


How to change the font family of axis labels in Chart.js?

To change the font family of axis labels in Chart.js, you can use the scales option of the chart configuration object.


Here's an example of how to change the font family for the x-axis labels:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['Label 1', 'Label 2', 'Label 3'],
        datasets: [{
            label: 'Dataset',
            data: [10, 20, 30]
        }]
    },
    options: {
        scales: {
            x: {
                ticks: {
                    font: {
                        family: 'Arial' // Specify the font family here
                    }
                }
            }
        }
    }
});


In the example above, we set the family property of the font object inside the ticks property of the x scale to 'Arial'. You can replace 'Arial' with the desired font family.


Similarly, you can change the font family for the y-axis labels by modifying the y scale:

1
2
3
4
5
6
7
8
9
scales: {
    y: {
        ticks: {
            font: {
                family: 'Arial' // Specify the font family here
            }
        }
    }
}


Make sure to replace 'Arial' with the desired font family.


How to create a combo chart with both bar and line elements using Chart.js?

To create a combo chart with both bar and line elements using Chart.js, you can use the type property of the configuration object to specify the type of chart for each dataset.


Here's an example that creates a combo chart with one dataset represented as bars and another dataset represented as a line:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// Get the canvas element
const ctx = document.getElementById('myChart').getContext('2d');

// Define the data for the chart
const data = {
  labels: ['January', 'February', 'March', 'April', 'May', 'June'],
  datasets: [
    {
      type: 'bar', // Dataset 1 is represented as bars
      label: 'Sales',
      data: [50, 75, 100, 65, 80, 120],
      backgroundColor: 'rgba(54, 162, 235, 0.5)',
      borderColor: 'rgba(54, 162, 235, 1)',
      borderWidth: 1
    },
    {
      type: 'line', // Dataset 2 is represented as a line
      label: 'Profit',
      data: [10, 20, 30, 25, 35, 50],
      borderColor: 'rgba(255, 99, 132, 1)',
      borderWidth: 2,
      fill: false
    }
  ]
};

// Create the chart
const chart = new Chart(ctx, {
  type: 'bar', // Start with a bar chart
  data: data,
  options: {
    responsive: true,
    plugins: {
      legend: {
        position: 'top'
      },
      title: {
        display: true,
        text: 'Combo Chart'
      }
    }
  }
});


In the above example, the type property is set to 'bar' for the first dataset and 'line' for the second dataset. This creates a combo chart with bars and a line. You can adjust the properties of each dataset, such as colors and labels, as needed.


How to create a stacked bar chart using Chart.js?

To create a stacked bar chart using Chart.js, you need to follow these steps:

  1. Include the Chart.js library in your HTML file by adding the following script tag in the section:
1
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>


  1. Create a canvas element in your HTML file where the chart will be rendered:
1
<canvas id="myChart"></canvas>


  1. Create a JavaScript code block in your HTML file, and inside it, define the data that will be used to create the chart:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<script>
  var ctx = document.getElementById('myChart').getContext('2d');
  var data = {
    labels: ['Group 1', 'Group 2', 'Group 3'],
    datasets: [
      {
        label: 'Dataset 1',
        data: [10, 20, 30],
        backgroundColor: 'rgba(255, 99, 132, 0.7)',
      },
      {
        label: 'Dataset 2',
        data: [40, 30, 20],
        backgroundColor: 'rgba(54, 162, 235, 0.7)',
      },
      {
        label: 'Dataset 3',
        data: [30, 10, 40],
        backgroundColor: 'rgba(75, 192, 192, 0.7)',
      }
    ]
  };
</script>


  1. Create the chart using the Chart constructor and the data defined in the previous step:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<script>
  var myChart = new Chart(ctx, {
    type: 'bar',
    data: data,
    options: {
      scales: {
          x: {
              stacked: true,
          },
          y: {
              stacked: true
          }
      }
    }
  });
</script>


In the above code, the type property is set to 'bar' to create a bar chart. The data for each dataset is provided as an array, and the backgroundColor property is used to specify the color of each bar.


The scales property in the chart options is set to {x: {stacked: true}, y: {stacked: true}} to stack the bars.

  1. That's it! When you load your HTML file in the browser, you will see the stacked bar chart rendered on the canvas element.


How to display legends in a horizontal layout with Chart.js?

To display legends in a horizontal layout with Chart.js, you can use the options provided by the library.


Here is an example of how to achieve this:

1
2
3
4
5
6
7
const chartOptions = {
  responsive: true,
  legend: {
    display: true,
    position: 'bottom', // Set the position to 'bottom' to display the legend horizontally
  },
};


In this example, we set the legend.display option to true to show the legend, and the legend.position option to 'bottom' to position the legend at the bottom of the chart horizontally.


You can then pass this chartOptions object as the options parameter when creating your chart using the Chart() constructor.

1
2
3
4
5
new Chart(ctx, {
  type: 'line',
  data: data,
  options: chartOptions,
});


Note that ctx is the 2D rendering context of the <canvas> element and data is the data object you are passing to the chart.


This will display the legends in a horizontal layout at the bottom of the chart. You can adjust the position and other styles of the legend according to your requirements.

Facebook Twitter LinkedIn Telegram

Related Posts:

To draw a tornado diagram using d3.js, you can follow these steps:Start by setting up your HTML file and include the d3.js library.Create a container element for your diagram, such as an SVG element.Use d3.js to create a dataset that represents the values you ...
To delete an instance of a chart using chart.js, you can first retrieve the chart instance that you want to delete by using the Chart.get(chartId) method. Once you have the chart instance, you can call the destroy() method on it to remove the chart from the DO...
To export a chart.js chart to Excel, you can follow these steps:Prepare your chart: Create a chart using the chart.js library in your web application. Make sure the chart is fully rendered and visible on the webpage. Include the necessary libraries: To perform...