使用chart.js和关联数组生成条形图 [英] Generate bar chart using chart.js and associative array

查看:67
本文介绍了使用chart.js和关联数组生成条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have associative array and I want to display it using Chart.JS library.

我的阵列:

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

例如:

1)信息技术具有类别值为2的电子学习,并且具有类别值为2的Webex

1) Information Technology has category ELearning with value 2 and has category Webex with value 2

2) Masscom 具有类别值为3的在线学习,并且具有类别值为3的Webex

2) Masscom has category ELearning with value 3 and has category Webex with value 3

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:

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

我创建了一个jsfiddle来显示正在运行的代码.

I created a jsfiddle to show the code running.

这篇关于使用chart.js和关联数组生成条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆