Create a simple Bar Graph using Javascript

Create a simple Bar Graph using Javascript

08-Nov-2023
| |
Image Carousel

Table of Contents

S.no Contents-topics
1 Introduction
2 HTML Code
3 Javascript code

1:Introduction

In this tutorial we will learn how we we'll create a bar chart with different colors for each bar in JavaScript using Chart.js,

2:HTML Code

In HTML body we will use simple id
HTML code:
Copy

<!DOCTYPE html>
<html>
<head>
<title>Bar Graph by DeveloperCodez</title>
</head>
<body>
<canvas id="myChart"></canvas>
</body>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</html>

3:Javascript code

js codeCopy

<script>
// Get the canvas element
var ctx = document.getElementById('myChart').getContext('2d');
 
// Define the chart data
var data = {
  labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
  datasets: [{
    label: 'day records',
    data: [12, 19, 3, 5, 2, 3],
      backgroundColor: [
      'rgba(255, 99, 132, 0.2)',
      'rgba(255, 159, 64, 0.2)',
      'rgba(255, 205, 86, 0.2)',
      'rgba(75, 192, 192, 0.2)',
      'rgba(54, 162, 235, 0.2)',
      'rgba(153, 102, 255, 0.2)',
      'rgba(201, 203, 207, 0.2)'
    ],
    borderColor: 'rgba(54, 162, 235, 1)', // Set the border color
    borderWidth: 1 // Set the border width
  }]
};
 
// Configure the chart options
var options = {
  responsive: true,
  maintainAspectRatio: false,
  scales: {
    y: {
      beginAtZero: true
    }
  }
};
 
// Create the chart
var myChart = new Chart(ctx, {
  type: 'bar',
  data: data,
  options: options
});
 
</script>

 

Tags: Bar colors , Bar width , Canvas element , Bar graph , JavaScript charting libraries , create a simple bar graph using javascript,JavaScript,
0 Comments (Please let us know your query)
Leave Comment
Leave Comment
Articles from other Categories
Load More

Newsletter