简体   繁体   English

使用 chart.js 和关联数组生成条形图

[英]Generate bar chart using chart.js and associative array

I have associative array and I want to display it using Chart.JS library.我有关联数组,我想使用 Chart.JS 库显示它。

My Array:我的阵列:

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
  ]
]

What I am trying to do:我想做什么:

I am trying to show: - Faculties at the bottom as labels - For each faculty I want to show all the category and its counter我试图展示: - 底部的学院作为标签 - 对于每个学院,我想展示所有类别及其计数器

eg:例如:

1) Information Technology has category ELearning with value 2 and has category Webex with value 2 1)信息技术具有值为 2 的类别 ELearning 和具有值为 2类别 Webex

2) Masscom has category ELearning with value 3 and has category Webex with value 3 2) Masscom具有值为 3 的类别ELearning 和具有值为 3 的类别 Webex

JS Code: JS代码:

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

Essentially, you will need a data set for each of your categories.本质上,您需要为每个类别创建一个数据集。 Each data set will need a data entry for each faculty.每个数据集都需要每个教员的数据条目。

Using the code below, you will get a chart that looks like this:使用下面的代码,您将获得如下所示的图表:

来自 JS 小提琴代码的图表

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

I created a jsfiddle to show the code running .我创建了一个 jsfiddle 来显示正在运行的代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM