Skip to main content

Creating a Simple Bar Graph using Chart.js Library Tutorial

Screenshot
Body

In this tutorial, we will tackle about how to create a Bar Graph using Chart.js. Chart.js is an open-source javascript library that focuses in generating a graphical canvases such as Line , Bar, and Pie Graphs. Here, I will be providin a source code that demonstrates how to generate a simple Bar Graph using the said javascript library.

The Bar Graph that I will show is a simple Annual Report within 3 years that has 3 types of data set each year which are the total Sales, Expenses, and Profit. I will be using Bootstrap page user-interface/design.

Getting Started

In this tutorial source code, I usedBootstrap v5 for the design of application, jQuery Library, and the most important is Chart.js Library.

Creating the Interface

First, I created an HTML scripts which contains the codes of the application interface. I save this file as index.html.

The code contains a simple top navigation bar, canvas tag where the graph will be shown, and a button for generate a new random data of the graph.

  1. <!DOCTYPE html>
  2. <html lang="en">
  3.  
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Chart.js</title>
  8. <link rel="stylesheet" href="./css/bootstrap.min.css">
  9. <script src="./js/jquery-3.6.0.min.js"></script>
  10. <script src="./js/bootstrap.min.js"></script>
  11. <script src="./js/chart.min.js"></script>
  12. <script src="./js/script.js"></script>
  13. :root {
  14. --bs-success-rgb: 71, 222, 152 !important;
  15. }
  16.  
  17. html,
  18. body {
  19. height: 100%;
  20. width: 100%;
  21. font-family: Apple Chancery, cursive;
  22. }
  23. </style>
  24. </head>
  25.  
  26. <body class="bg-light">
  27. <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient" id="topNavBar">
  28. <div class="container">
  29. <a class="navbar-brand" href="https://sourcecodester.com">
  30. Sourcecodester
  31. </a>
  32. </div>
  33. </nav>
  34. <div class="container py-3" id="page-container">
  35. <small>How to Create a Bar Graph using Chart.js</small>
  36. <hr>
  37.  
  38. <canvas id="chartCanvas" class="w-100" style="height: 60vh"></canvas>
  39. <center><button class="btn btn-sm btn-primary rounded-pill col-md-4" type="button" onclick="regenerate()">Randomize Data</button></center>
  40. </div>
  41.  
  42. </body>
  43.  
  44. </html>

Creating the Main Function

The following script is main script for the application which contains the Bar Charts Initilization, generating Randow Data values, and the function of Generating new Random Value of the Graph. I save this file as script.js.

  1. var ctx,
  2. myChart;
  3. // Simple Function for generating a Ranfom value
  4. function randomNumber() {
  5. return Math.random() * (String(999999999).substring(Math.floor(Math.random * 9) + 3))
  6. }
  7.  
  8. // Function for Generate a New Ranom Data of the Graph
  9. function regenerate() {
  10. // looping the number of chart's data sets
  11. Object.keys(myChart.data.datasets).map(k => {
  12. var set = myChart.data.datasets[k];
  13. // Updating the data values
  14. set.data = [randomNumber(), randomNumber(), randomNumber()]
  15. })
  16.  
  17. // Triggers Chart to display the updated Data
  18. myChart.update()
  19. }
  20. $(function() {
  21. // Canvas Element where to display the Bar Graph
  22. ctx = $('#chartCanvas');
  23. // Initializing the bar graph data and options
  24. myChart = new Chart(ctx, {
  25. type: 'bar',
  26. data: {
  27. labels: ['2017', '2018', '2019'],
  28. datasets: [{
  29. label: 'Sales',
  30. data: [randomNumber(), randomNumber(), randomNumber()],
  31. backgroundColor: "#1a93f0"
  32. }, {
  33. label: 'Expense',
  34. data: [randomNumber(), randomNumber(), randomNumber()],
  35. backgroundColor: "#e85454"
  36. }, {
  37. label: 'Profit',
  38. data: [randomNumber(), randomNumber(), randomNumber()],
  39. backgroundColor: "#74f29a"
  40. }]
  41. },
  42. options: {
  43. scales: {
  44. y: {
  45. beginAtZero: true,
  46. ticks: {
  47. // Customizing Y Axes Label
  48. callback: function(value) {
  49. parseFloat(value)
  50. if (value >= 100000 && value < 1000000) {
  51. value = String(value).substring(0, 3) + "K"
  52. } else if (value >= 1000000 && value < 1000000000) {
  53. if (String(value).length == 7)
  54. value = String(value).substring(0, 1) + "M"
  55. if (String(value).length == 8)
  56. value = String(value).substring(0, 2) + "M"
  57. if (String(value).length == 9)
  58. value = String(value).substring(0, 3) + "M"
  59. } else if (value >= 1000000000 && value <= 1000000000000) {
  60. if (String(value).length == 10)
  61. value = String(value).substring(0, 1) + "B"
  62. if (String(value).length == 11)
  63. value = String(value).substring(0, 2) + "B"
  64. if (String(value).length == 12)
  65. value = String(value).substring(0, 3) + "B"
  66. } else {
  67. value = (value).toLocaleString('en-US')
  68. }
  69.  
  70. return "$ " + value;
  71. }
  72. }
  73. }
  74. },
  75. plugins: {
  76. legend: {
  77. display: true
  78. },
  79. title: {
  80. display: true,
  81. text: 'Annual Report'
  82. }
  83. }
  84. }
  85. });
  86. })

Result

Bar Graph using Chart JS

DEMO VIDEO

That's the end of this tutorial. I hope this tutorial will help you and your future web application projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding :)

Add new comment