Categories
Chart.js JavaScript

Chart.js Bar Chart Example

Spread the love

Creating a bar chart isn’t very hard with Chart.js.

In this article, we’ll look at a Chart.js bar chart example to see how we can create a simple bar chart with little effort.

First, we have to include the Chart.js library. It uses the canvas to render chart data.

So, we have to write:

<script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js'></script>

<canvas id="barChart" width="400" height="400"></canvas>

To add Chart.js and our canvas.

Then we can write the following JavaScript code to create our bar chart:

const ctx = document.getElementById('barChart').getContext('2d');

const colorLabels = ['red', 'green', 'blue', 'yellow', 'orange']

const chart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: colorLabels,
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2],
      borderWidth: 1,
      backgroundColor: colorLabels
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

We set the labels property to set the labels at the x-axis.

The data array has the bar heights.

borderWidth sets the border widths of the bars.

backgroundColor set the colors of the bars.

In the options property, we have the yAxes property, which is an array.

In the array entry, we have the ticks property, which has the beginAtZero property set to true so that the y-axis starts at zero instead of the value of the shortest bar, which is 2.

Then we get:

https://thewebdev.info/wp-content/uploads/2020/04/barchart.png

As we can see from the Chart.js bar chart example we have above, it’s a simple task to create a bar chart from any existing data.

Leave a Reply

Your email address will not be published. Required fields are marked *