How to display a barchart in chart.js?

by jasen_gottlieb , in category: Javascript , 2 months ago

How to display a barchart in chart.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jerad , 2 months ago

@jasen_gottlieb 

To display a bar chart in Chart.js, you need to first include the Chart.js library in your HTML file. You can either download and include the library directly or include it from a CDN by adding the following script tag to your HTML file:

1
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>


Next, you need to create a canvas element where the chart will be displayed. For example:

1
<canvas id="myChart" width="400" height="400"></canvas>


Then, you need to create a script block with JavaScript code to create and customize the bar chart. Here is an example code snippet to create a simple bar chart:

 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
<script>
    var ctx = document.getElementById('myChart').getContext('2d');
    var myChart = 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
                }
            }
        }
    });
</script>


This code creates a simple bar chart with random data for demonstration purposes. You can customize the chart by modifying the labels, data, colors, and other options inside the myChart object.


After adding this code to your HTML file, you should see a bar chart displayed in the canvas element specified by the id attribute (myChart in this example).