Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
chart.js
histogram
communitycreator

Chart.js - Create a Histogram

John Au-Yeung

We can create a histogram with Chart.js without any problem.

All we have to do is to create a bar chart with some tweaks.

HTML

To start, we add Chart.js for the chart and the canvas for Chart.js to render the chart.

We add them by writing the following HTML:

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

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

JavaScript

Next, we create our histogram by writing some JavaScript code:

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

const chart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: [0, 1, 2, 3, 4],
    datasets: [{
      label: 'Number of Arrivals',
      data: [19, 28, 20, 16],
      backgroundColor: 'green',
    }]
  },
  options: {
    scales: {
      xAxes: [{
        display: false,
        barPercentage: 1.3,
        ticks: {
          max: 3,
        }
      }, {
        display: true,
        ticks: {
          autoSkip: false,
          max: 4,
        }
      }],
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

We render the chart with the canvas element with the ID histogram, as we indicated in the code. In the object that we passed into the Chart constructor, we set the type to 'bar' to display a bar chart. In line 7, datasets, we add our data property to set the bar heights. In line 6, labels are the names that are displayed on the horizontal axis. label is displayed above the histogram. Then, we have to adjust the x-axis options by setting the ticks maximum to 4 to adjust them. We make the bars wider than the typical graph by setting barPercentage to 1.3 so that the 4 bars are evenly distributed between the 5 ticks of the x-axis. autoSkip set to false means that automatic calculation of how many labels can be shown or hidden is false, which lets us override the ticks with the ones we mentioned above. autoSkip being false means that we always show all labels. beginAtZero being true means that we start the y-axis at 0.

Code

The running widget below demonstrates the above code.

We can see the green bars and that the bar is between 2 ticks rather than the bar being right above each tick.

RELATED TAGS

javascript
chart.js
histogram
communitycreator
RELATED COURSES

View all Courses

Keep Exploring