Chartjs-Bar chart with multiple datasets – Chart.JS

1👍

Assume that you are successfully getting the data from the controller with

var data = @Html.Raw(System.Text.Json.JsonSerializer.Serialize(Model.GetWeeklyData.ToList()))

You should group the data with the x-axis as the set of FormattedAccessDate.
In each FormattedAccessDate, there should be the bars for each ShiftName and its value as AttendancePercentage.

For the color settings (backgroundColor and borderColor), you can write the implementation to set the color value by the ShiftName or use the default color provided by the Chart.js via don’t provide the values for backgroundColor and borderColor. It is optional.

let labels = [...new Set(data.map(x => x.FormattedAccessDate))];
let datasets = data.reduce(function (acc, cur) {
  let shift = acc.find(x => x.label == cur.ShiftName);
  if (shift == null) {
    let color = '';
    
    switch (cur.ShiftName) {
      case 'First Shift':
        color = '#7F1E5E';
        break;
      case 'Second Shift':
        color = '#CE6D28';
        break;
      case 'Third Shift':
        color = '#005486';
        break;
    }
  
    shift = {
      label: cur.ShiftName,
      data: [cur.AttendancePercentage],
      backgroundColor: color,
      borderColor: color,
      borderWidth: 1
    };
    
    acc.push(shift);
  } else {
    shift.data.push(cur.AttendancePercentage);
  }
  
  return acc;
}, []);

var barChartDataDaily = {
  type: 'bar',
  data: {
    labels: labels,
    datasets: datasets
  }
};

const ctx = document.getElementById('myChart');
new Chart(ctx, barChartDataDaily);

Demo @ StackBlitz

Reference: Vertical Bar Chart

Leave a comment