具有多个数据集的条形图 - Chart Js

问题描述 投票:0回答:1

我想显示包含多个数据集的条形图,如下所示,

我能够获取如下所示的数据

但是如何转换这个json数组,如下代码。我需要显示过去 7 天每个班次的出勤率。

var barChartDataDaily = {
        labels: [@Html.Raw("'" + String.Join("','", (Model.GetWeeklyData.GroupBy(c => c.FormattedAccessDate).Select(c => c.First().FormattedAccessDate).ToList()))+"'" )],
        datasets: [
            {
                label: "First Shift",
                backgroundColor: "#7F1E5E",
                borderColor: "#7F1E5E",
                borderWidth: 1,
                data: [14, 27, 33, 46, 100, 67, 74]
            },
            {
                label: "Second Shift",
                backgroundColor: "#CE6D28",
                borderColor: "#CE6D28",
                borderWidth: 1,
                data: [14, 27, 33, 46, 100, 67, 74]
            },
            {
                label: "Third Shift",
                backgroundColor: "#005486",
                borderColor: "#005486",
                borderWidth: 1,
                data: [100, 27, 34, 56, 69, 87, 73]
            }
        ]
    };

感谢您为此提供的帮助。谢谢!

==================已编辑==================

//X-axis labels
var groupname = [@Html.Raw("'" + String.Join("','", (Model.GetWeeklyData.GroupBy(c => c.FormattedAccessDate).Select(c => c.First().FormattedAccessDate).ToList()))+"'" )];
 
//Fetched Array
    var data = @Html.Raw(System.Text.Json.JsonSerializer.Serialize(Model.GetWeeklyData.ToList()))
javascript asp.net-core chart.js
1个回答
0
投票

假设您已成功从控制器获取数据

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

您应该将 x 轴的数据分组为

FormattedAccessDate
的集合。 在每个
FormattedAccessDate
中,应该有每个
ShiftName
的条形,其值为
AttendancePercentage

对于颜色设置(

backgroundColor
borderColor
),您可以编写实现来通过
ShiftName
设置颜色值,或者使用Chart.js提供的默认颜色,通过不提供
的值backgroundColor
borderColor
。这是可选的。

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);

演示@StackBlitz

参考:垂直条形图

© www.soinside.com 2019 - 2024. All rights reserved.