Category: chart

Integrate Bar chart using chart.js in the website

To create a bar chart using Chart.js, you can follow these steps:

  1. Include the Chart.js library in your HTML file:
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  1. Create a canvas element in your HTML file where the chart will be displayed:
<canvas id="myChart"></canvas>
  1. Define the data for the chart in a JavaScript array:
var data = {
    labels: ["January", "February", "March", "April", "May"],
    datasets: [
        {
            label: "My First Dataset",
            backgroundColor: "rgba(255,99,132,0.2)",
            borderColor: "rgba(255,99,132,1)",
            borderWidth: 1,
            hoverBackgroundColor: "rgba(255,99,132,0.4)",
            hoverBorderColor: "rgba(255,99,132,1)",
            data: [30, 50, 80, 60, 70],
        }
    ]
};

In this example, we define an array with five labels and one dataset containing an array of five values.

  1. Create the chart using the Chart constructor:
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx, {
    type: 'bar',
    data: data,
});

In this example, we specify the type of chart (bar) and the data to be used for the chart.

  1. Customize the chart as needed using Chart.js options. For example, to change the chart title, you can add the following option:
options: {
    title: {
        display: true,
        text: 'My Chart Title'
    }
}

The complete code would look like this:

<!DOCTYPE html>
<html>
<head>
    <title>My Chart</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
    <canvas id="myChart"></canvas>
    <script>
        var data = {
            labels: ["January", "February", "March", "April", "May"],
            datasets: [
                {
                    label: "My First Dataset",
                    backgroundColor: "rgba(255,99,132,0.2)",
                    borderColor: "rgba(255,99,132,1)",
                    borderWidth: 1,
                    hoverBackgroundColor: "rgba(255,99,132,0.4)",
                    hoverBorderColor: "rgba(255,99,132,1)",
                    data: [30, 50, 80, 60, 70],
                }
            ]
        };

        var ctx = document.getElementById("myChart").getContext("2d");
        var myChart = new Chart(ctx, {
            type: 'bar',
            data: data,
            options: {
                title: {
                    display: true,
                    text: 'My Chart Title'
                }
            }
        });
    </script>
</body>
</html>

This will create a bar chart with the data and options specified. You can customize the appearance of the chart further using Chart.js options, such as setting the axis labels, changing the colors of the bars, and adding animations.