Dynamic Bar, Line, and Pie Chart Data using Chart.js Tutorial

Introduction

In this tutorial, you will learn how to Create a Bar, Line, and Pie Chart using ChartJS Library with dynamic data values. The tutorial aims to provide a reference or guide to students or new programmers on how to use and implement Charts in web applications. Here, snippets of creating the charts and generating dynamic values are provided and a sample web app source code zip file is also provided and is free to download.

What is ChartJS

ChartJS is a community-maintained project. It is a JavaScript Plugin or Library that helps developers to generate different kinds of charts for their web projects. The said plugin can generate 8 different types of charts that can provide end-users with a visual view of the data values. Visit ChartJS Official Website to know more.

How to Create a Bar, Line, and Pie Chart?

Developers often use charts to provide the end-users with a better visual representation of data. In some instances, developers do need to display the charts with dynamic data values that are commonly stored in a database or generated from a certain logic that we created to meet our requirements. ChartJS provides consideration for the developers to easily manipulate the datasets in the generated Chart. By that, developers can simply use the provided API or script for this to update the chart even without needing to reload the page.

Example Snippets

Here are some examples of creating a Bar, Line, or Pie chart with dynamic data values using the ChartJS plugin.

The snippets below use the following function constant and function for the chart colors and randomly generate a data value. I used the Bootstrap v5 framework for the interface design on the snippets.

  1. const colors = ['#AAC4FF', '#CDF0EA', "#6E85B7", '#68A7AD'];
  2. const labels = ["Data 101", "Data 102", "Data 103", "Data 104"]
  3.  
  4. function rand_num(){
  5. return Math.floor( Math.random() * (9999 - 1) + 1 );
  6. }

Creating a Bar Chart

Here are the snippets to generate a Bar Chart in a web application using ChartJS.

HTML

  1. <div class="card shadow rounded-0">
  2. <div class="card-header rounded-0">
  3. <div class="d-flex justify-content-between">
  4. <div class="card-title flex-shrink-1 flex-grow-1">Bar Chart</div>
  5. <div class="col-auto">
  6. <button class="btn btn-primary btn-sm rounded-0" id="generate_bar">Generate Random</button>
  7. </div>
  8. </div>
  9. </div>
  10. <div class="card-body">
  11. <div class="container-fluid">
  12. <canvas id="bar_chart"></canvas>
  13. </div>
  14. </div>
  15. </div>

JavaScript

  1. /**
  2. * Bar Chart
  3. */
  4.  
  5. const default_value = [rand_num(), rand_num(), rand_num(), rand_num()]
  6. const default_value2 = [rand_num(), rand_num(), rand_num(), rand_num()]
  7. const barChart = new Chart(document.getElementById('bar_chart').getContext('2d'), {
  8. type: 'bar',
  9. data:{
  10. labels:labels,
  11. datasets: [{
  12. label: "Sample Bar Chart",
  13. data: default_value,
  14. backgroundColor: colors,
  15. borderColor: colors,
  16. borderWidth: 1
  17. }]
  18. },
  19. options:{
  20. scales: {
  21. y: {
  22. beginAtZero: true
  23. }
  24. }
  25. }
  26. })
  27.  
  28. $('#generate_bar').click(function(){
  29. var new_values = [rand_num(), rand_num(), rand_num(), rand_num()]
  30. /**
  31.   * You can get your dynamic values from other page or file
  32.   * i.e
  33.   * $.ajax({
  34.   * url:'dynamic_data.php?id=1',
  35.   * dataType:'JSON',
  36.   * success: function(response){
  37.   * values = Object.values(response)
  38.   * }
  39.   * })
  40.   */
  41.  
  42. /**
  43.   * After getting the new values, Update the dataset's data
  44.   */
  45. barChart.data.datasets[0].data = new_values
  46.  
  47. /**
  48.   * Then Update the Chart
  49.   */
  50.  
  51. barChart.update()
  52. })

Result Snapshot

ChartJS - Bar Chart Example

Creating a Line Chart

Here are the snippets to generate a Line Chart in a web application using ChartJS.

HTML

  1. <div class="card shadow rounded-0">
  2. <div class="card-header rounded-0">
  3. <div class="d-flex justify-content-between">
  4. <div class="card-title flex-shrink-1 flex-grow-1">Line Chart</div>
  5. <div class="col-auto">
  6. <button class="btn btn-primary btn-sm rounded-0" id="generate_line">Generate Random</button>
  7. </div>
  8. </div>
  9. </div>
  10. <div class="card-body">
  11. <div class="container-fluid">
  12. <canvas id="line_chart"></canvas>
  13. </div>
  14. </div>
  15. </div>

JavaScript

  1. /**
  2. * Line Chart
  3. */
  4.  
  5. const lineChart = new Chart(document.getElementById('line_chart').getContext('2d'), {
  6. type: 'line',
  7. data:{
  8. labels:labels,
  9. datasets: [{
  10. label: "Sample Data 1",
  11. data: default_value,
  12. borderColor: colors[Math.floor( Math.random() * (3 - 0) + 1 )],
  13. fill:false,
  14. tension: 0.2
  15. },
  16. {
  17. label: "Sample Data 2",
  18. data: default_value2,
  19. borderColor: colors[Math.floor( Math.random() * (3 - 0) + 1 )],
  20. fill:false,
  21. tension: 0.2
  22. }
  23. ]
  24. },
  25. options:{
  26. scales: {
  27. y: {
  28. beginAtZero: true
  29. }
  30. }
  31. }
  32. })
  33.  
  34. $('#generate_line').click(function(){
  35. var new_values = [rand_num(), rand_num(), rand_num(), rand_num()]
  36. var new_values2 = [rand_num(), rand_num(), rand_num(), rand_num()]
  37. /**
  38.   * You can get your dynamic values from other page or file
  39.   * i.e
  40.   * $.ajax({
  41.   * url:'dynamic_data.php?id=1',
  42.   * dataType:'JSON',
  43.   * success: function(response){
  44.   * values = Object.values(response)
  45.   * }
  46.   * })
  47.   */
  48.  
  49. /**
  50.   * After getting the new values, Update the dataset's data
  51.   */
  52. lineChart.data.datasets[0].data = new_values
  53. lineChart.data.datasets[0].borderColor = colors[Math.floor( Math.random() * (3 - 0) + 1 )]
  54.  
  55. lineChart.data.datasets[1].data = new_values2
  56. lineChart.data.datasets[1].borderColor = colors[Math.floor( Math.random() * (3 - 0) + 1 )]
  57.  
  58. /**
  59.   * Then Update the Chart
  60.   */
  61.  
  62. lineChart.update()
  63. })

Result Snapshot

ChartJS - Line Chart Example

Creating a Pie Chart

Here are the snippets to generate a Pie Chart in a web application using ChartJS.

HTML

  1. <div class="card shadow rounded-0">
  2. <div class="card-header rounded-0">
  3. <div class="d-flex justify-content-between">
  4. <div class="card-title flex-shrink-1 flex-grow-1">Pie Chart</div>
  5. <div class="col-auto">
  6. <button class="btn btn-primary btn-sm rounded-0" id="generate_pie">Generate Random</button>
  7. </div>
  8. </div>
  9. </div>
  10. <div class="card-body">
  11. <div class="container-fluid">
  12. <canvas id="pie_chart"></canvas>
  13. </div>
  14. </div>
  15. </div>

JavaScript

  1. /**
  2. * pie Chart
  3. */
  4.  
  5. const pieChart = new Chart(document.getElementById('pie_chart').getContext('2d'), {
  6. type: 'pie',
  7. data:{
  8. labels:labels,
  9. datasets: [{
  10. label: "Sample Pie Chart",
  11. data: default_value,
  12. backgroundColor: colors,
  13. }
  14. ],
  15. hoverOffset: 4
  16. },
  17. })
  18.  
  19. $('#generate_pie').click(function(){
  20. var new_values = [rand_num(), rand_num(), rand_num(), rand_num()]
  21. /**
  22.   * You can get your dynamic values from other page or file
  23.   * i.e
  24.   * $.ajax({
  25.   * url:'dynamic_data.php?id=1',
  26.   * dataType:'JSON',
  27.   * success: function(response){
  28.   * values = Object.values(response)
  29.   * }
  30.   * })
  31.   */
  32.  
  33. /**
  34.   * After getting the new values, Update the dataset's data
  35.   */
  36. pieChart.data.datasets[0].data = new_values
  37.  
  38. /**
  39.   * Then Update the Chart
  40.   */
  41.  
  42. pieChart.update()
  43. })

Result Snapshot

ChartJS - Pie Chart Example

On the above snippets, each chart data value can be manipulated and randomly set the data sets value by clicking the Generate Random button. Doing so, the application will automatically generate new random data value for each chart and automatically updates the displayed chart to its updated values.

Combined Charts Snapshot

ChartJS - Bar, line, and Pie Chart Example

That's the end of this tutorial. I hope this Dynamic Bar, Line, and Pie Chart using ChartJS Tutorial will help you with what you are looking for and that you'll find this useful for your current and future projects. I have also provided the source code zip file that combines the snippet above. Feel free to download it by clicking the download button below.

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

Happy Coding:)

Comments

Submitted byjjmono (not verified)on Tue, 11/15/2022 - 10:40

Hi sir, can you share me project file or provide download link. Absolutely need for my project.

Add new comment