输入数据
Engine,Car,Brand,Efficiency
ABC212,Toyota Corolla,Toyota,1.95
ABC212,Toyota Yaris,Toyota,1.94
ABC212,Totyota Etios,Toyota,1.93
ABC212,Honda City,Honda,1.93
ABC212A,Honda Brio,Honda,1.91
DEF311,Toyota Camry,Toyota,1.90
DEF310,Toyota Prius,Toyota,1.82
DEF310,Ford Explorer,Ford,1.85
DEF310,Ford Endeavour,Ford,1.83
DEF305,Ford Fugo,Ford,1.79
使用上述数据,我需要在ChartJs
中使用多级x轴创建一个图表。使用MS excel数据透视图创建的预期输出如下。此处,每个模型的效率均以条形图表示。每组中的条按效率值的降序排列。我应该如何为这种图表创建数据?
答案 0 :(得分:1)
我已经在使用的POC中制作了这样的图形:
data: {
labels: ["ABC212", "ABC212A",...],
datasets: [
{
label: "ABC212",
data: [val1, val2,....]
}, {
label: "ABC212A",
data: [val3, val4,...]
}
]
}
答案 1 :(得分:0)
在不确定这是最简单的解决方案的情况下,我提供了一些示例,其中我使用了第二个轴,其中包含组的标签,但按比例放大的数组用于正确对齐。
唯一的问题是,如果为组maxRotation>0
启用旋转功能,则文本将始终旋转,因为(由于缩放)该文本绑定到很小的区域。
https://jsfiddle.net/h6z4apvo/
var myData = [
["ABC212","Toyota Corolla","Toyota",1.95],
["ABC212","Toyota Yaris","Toyota",1.94],
["ABC212","Totyota Etios","Toyota",1.93],
["ABC212","Honda City","Honda",1.93],
["ABC212A","Honda Brio","Honda",1.91],
["DEF311","Toyota Camry","Toyota",1.90],
["DEF310","Toyota Prius","Toyota",1.82],
["DEF310","Ford Explorer","Ford",1.85],
["DEF310","Ford Endeavour","Ford",1.83],
["DEF305","Ford Fugo","Ford",1.79]
];
/*Calculates group labels to a scaled array so that they can align better*/
function calculateGroupLabels(data){
const scaleFactor=100;
var labels = _(data)
.groupBy((elem)=>elem[0])
.map((entriesOnSameGroup, key)=>{
var newSize = entriesOnSameGroup.length*scaleFactor;
var newArray = new Array(newSize);
newArray[0]="";
newArray[newArray.length-1]="";
newArray[parseInt((newArray.length-1)/2)]=key;
return newArray;
}).flatten().value()
return labels;
}
var labels = calculateGroupLabels(myData);
var ctx = $("#c");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
datasets: [{
label: '# of Votes',
xAxisID:'modelAxis',
data: myData.map((entry)=>entry[3])
}]
},
options:{
scales:{
xAxes:[
{
id:'modelAxis',
type:"category",
ticks:{
//maxRotation:0,
autoSkip: false,
callback:function(label, x2, x3, x4){
console.log("modelAxis", label, x2, x3, x4)
return label;
}
},
labels:myData.map((entry=>entry[1]))
},
{
id:'groupAxis',
type:"category",
gridLines: {
drawOnChartArea: false,
},
ticks:{
padding:0,
maxRotation:0,
autoSkip: false,
callback:function(label){
return label;
}
},
labels:labels
}],
yAxes:[{
ticks:{
beginAtZero:true
}
}]
}
}
});