DEV Community

Cover image for Getting Started with Chart.js – Make Beautiful Charts with Just a Few Lines of Code
gauharnawab
gauharnawab

Posted on

Getting Started with Chart.js – Make Beautiful Charts with Just a Few Lines of Code

Hey there, aspiring developers! 👋

Ever looked at fancy websites with colorful charts and thought, "How do they do that?"
Well, today you're going to learn how to make your very own bar chart using a cool and beginner-friendly library called Chart.js!

What is Chart.js?

Chart.js is a simple JavaScript library that helps you create awesome and interactive charts (like bar charts, line charts, pie charts, and more!) using just a little bit of code.

It's super handy for:

  • Showing data in a visual way 📊
  • Making dashboards and reports prettier 🌈
  • Learning how JavaScript and data visualization work together 🤓

Step-by-Step: Let’s Build a Bar Chart

_1️⃣ Include Chart.js in Your HTML

You can add Chart.js to your project using a CDN (Content Delivery Network) — no need to download anything!_

Just add this line inside the

of your HTML:
<head> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> </head> 
Enter fullscreen mode Exit fullscreen mode

_2️⃣ Add a Element for the Chart
This is like a blank canvas where your chart will be painted! _

<body> <h2>My First Bar Chart</h2> <canvas id="myChart" width="400" height="200"></canvas> </body> 
Enter fullscreen mode Exit fullscreen mode

3️⃣ Style It Using Basic CSS
Let’s add some simple styles to center the chart and make it look nice:

<style> body { font-family: Arial, sans-serif; text-align: center; background-color: #f9f9f9; padding: 20px; } canvas { background: #ffffff; border: 1px solid #ddd; padding: 10px; box-shadow: 0 4px 8px rgba(0,0,0,0.1); } </style> 
Enter fullscreen mode Exit fullscreen mode

4️⃣ Add JavaScript to Create a Basic Bar Chart
Now comes the fun part — using JavaScript to make the chart appear!

<script> const ctx = document.getElementById('myChart').getContext('2d'); const myChart = new Chart(ctx, { type: 'bar', // Type of chart data: { labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'], // X-axis labels datasets: [{ label: 'Votes', data: [12, 19, 3, 5, 2, 3], // Y-axis values backgroundColor: [ 'rgba(255, 99, 132, 0.6)', 'rgba(54, 162, 235, 0.6)', 'rgba(255, 206, 86, 0.6)', 'rgba(75, 192, 192, 0.6)', 'rgba(153, 102, 255, 0.6)', 'rgba(255, 159, 64, 0.6)' ], borderColor: 'rgba(0, 0, 0, 0.1)', borderWidth: 1 }] }, options: { scales: { y: { beginAtZero: true // Start Y-axis from 0 } } } }); </script> 
Enter fullscreen mode Exit fullscreen mode

_Tips for Beginners:
_

  • Don’t be afraid to experiment! Try changing the colors or the data values.
  • If something breaks, check your browser console (right-click > Inspect > Console tab).
  • Want to try other charts? Just change type: 'bar' to 'line', 'pie', or 'doughnut'!

Top comments (0)