【问题标题】:Generate bar chart using chart.js and associative array使用 chart.js 和关联数组生成条形图
【发布时间】:2019-04-13 01:59:58
【问题描述】:

我有关联数组,我想使用 Chart.JS 库显示它。

我的数组:

array:4 [▼
  0 => array:3 [▼
    "faculty" => "Information Technology"
    "category" => "ELearning"
    "counter" => 2
  ]
  1 => array:3 [▼
    "faculty" => "Information Technology"
    "category" => "Webex"
    "counter" => 2
  ]
  2 => array:3 [▼
    "faculty" => "Masscom"
    "category" => "ELearning"
    "counter" => 3
  ]
  3 => array:3 [▼
    "faculty" => "Masscom"
    "category" => "Webex"
    "counter" => 3
  ]
]

我想做什么:

我试图展示: - 底部的院系作为标签 - 对于每个教师,我想显示所有类别及其计数器

例如:

1) 信息技术价值2的类别ELearning价值2的类别Webex

2) Masscom 具有 ELearning 类别价值 3Webex 类别价值 3

JS代码:

var faculties = ['Information Technology', 'Masscom'];
var f = document.getElementById("mybarChart");
new Chart(f, {
    type: "bar",
    data: {
       labels: faculties,
       datasets: ....
    },
})

【问题讨论】:

    标签: javascript arrays chart.js associative-array


    【解决方案1】:

    基本上,您需要为每个类别创建一个数据集。每个数据集都需要每个教员的数据条目。

    使用下面的代码,您将得到一个如下所示的图表:

    // this will get distinct faculty and sort
    const faculties = [...new Set(data.map(v => v['faculty']))].sort();
    
    // this will get distinct category and sort
    const categories = [...new Set(data.map(v => v['category']))].sort();
    
    const datasets = categories.map(category => ({
      label: category,
      data: faculties.map(faculty => {
        const value = data.find(v => v['faculty'] === faculty && v['category'] === category);
    
        return value['counter'];
      })
    }));
    
    const canvas = document.getElementById('mybarChart');
    
    new Chart(canvas, {
      type: 'bar',
      data: {
        labels: faculties,
        datasets: datasets
      }
    });
    

    我为show the code running 创建了一个jsfiddle。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-02
      • 2012-11-28
      • 2015-03-26
      相关资源
      最近更新 更多