Menu Close

Chart.js Bar Chart Example

bar-chat

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:

Chart.js bar chart example

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.

As we can see from the Chart.js time series example above, it doesn’t take much effort to display simple time-series data with it.

Posted in HTML, JavaScript

You can also read...