Chartjs-ChartJS vertical bar chart – measure percentage of the data in each column based on a specified max

1πŸ‘

βœ…

The solution heavily depends on the format of your base data. It could for example be defined as follows:

const testResults = [
  { category: 'Algebra', totalQuestions: 10, correclyAnswered: 7 },
  { category: 'Calculus', totalQuestions: 12, correclyAnswered: 9 },
  { category: 'Analysis', totalQuestions: 8, correclyAnswered: 5 },
  { category: 'Geometry ', totalQuestions: 10, correclyAnswered: 10 },
  { category: 'Combinatorics ', totalQuestions: 9, correclyAnswered: 5 }
];

In this case, the chart data could be generated in the following way:

const data = {
  labels: testResults.map(o => o.category),
  datasets: [
    {
      label: 'Test Results',
      backgroundColor: 'rgba(0, 255, 0, 0.2)',
      borderColor: 'rgba(0, 255, 0)',
      borderWidth: 1,
      data: testResults.map(o => (100 / o.totalQuestions * o.correclyAnswered))
    }
  ]
};

Then you would also have to define chart options to make sure tooltips and labels are properly formatted and the x-axis spreads full with between 0 and 100 %.

const options = {      
  tooltips: {
    callbacks: {
      label: (tooltipItem, data) => {
        var label = data.datasets[tooltipItem.datasetIndex].label || '';
        return label + ': ' + tooltipItem.xLabel.toFixed(0) + '%';
      }
    }
  },
  scales: {
    xAxes: [{
      ticks: {
        min: 0,
        max: 100,
        stepSize: 10,
        callback: value => value + '%'
      } 
    }]
  }
}

The chart itself would be defined as follows:

<HorizontalBar 
  data = { data } 
  options = { options } 
/>

Please have a look at this StackBlitz.

Leave a comment