make a histogram in javascript

To make a histogram in JavaScript, we can use Chart.js library. Here's an example code to create a simple histogram using Chart.js:

index.tsx
//HTML
<canvas id="myChart"></canvas>

//JavaScript
const data = {
  labels: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'], //labels for x-axis
  datasets: [{
    label: 'Data', //label for legend
    data: [12, 19, 3, 5, 2, 3, 8, 5, 12, 10], // data array for y-axis
    backgroundColor: 'rgba(54, 162, 235, 0.2)', //color of the bars
    borderColor: 'rgba(54, 162, 235)', //border color of the bars
    borderWidth: 1 //border width of the bars
  }]
}

const config = {
  type: 'bar',
  data: data,
  options: {
    scales: {
      y: {
        beginAtZero: true //start the y-axis from 0
      }
    }
  }
};

const myChart = new Chart(
  document.getElementById('myChart'),
  config
);
697 chars
32 lines

In this example, we have used an array of data for the y-axis and labels for the x-axis. We have also defined the style of the bars using backgroundColor, borderColor and borderWidth properties. Finally, we have created a new Chart instance with the bar type and passed in the data and options.

gistlibby LogSnag