我正在尝试创建一个堆积的条形图,其中组中的每个条形图部分将包含两个数据,一个计数和一个成本。我希望计数反映在栏中,我希望成本显示在栏中标签。
我还希望能够在工具提示中同时显示计数和成本。
这有可能吗,最简单的方法是什么?
答案 0 :(得分:1)
这可能是您想要的:
var final = Object.assign({}, default, settings);
var matrix = [
{//cat1 - position 0
Low: { cost: 10, count: 2},
Medium: { cost: 100, count: 20},
High: { cost: 1000, count: 40}
},
{//cat2 - position 1
Low: { cost: 20, count: 4},
Medium: { cost: 200, count: 40},
High: { cost: 2000, count: 60}
},
{//cat3 - position 2
Low: { cost: 30, count: 6},
Medium: { cost: 300, count: 60},
High: { cost: 3000, count: 80}
}];
//countsData can be build using matrix
var countsData = [
['Low', 2, 4, 6],
['Medium', 20, 40, 60],
['High', 40, 60, 80],
];
var riskToColor = {
Low: '#9ACD32',
Medium: '#FFD700',
High: '#FF4500'
};
var categoriesList = ['cat1', 'cat2', 'cat3'];
var chart = c3.generate({
bindto: '#cool-chart',
size: {
height: 200
},
data: {
columns: countsData,
type: 'bar',
colors: riskToColor,
groups: [
['Low', 'Medium', 'High']
],
order: null,
labels: {
format: function (v, id, i, j) {
if(i !== undefined) {
// console.log(i+" " + matrix[i][id]['cost']);
return matrix[i][id]['cost'] + "$";
}
else return v;
}},
},
axis: {
rotated: true,
x: {
type: 'category',
categories: categoriesList
},
y: {show: false}
},
tooltip: {
contents: function (d) {
var $$ = this, config = $$.config,text;
console.log(d[0]);
text = "<table class='" + $$.CLASS.tooltip + "'><tr><th colspan='3'>"+categoriesList[d[0].index]+"</th></tr>";
text += "<tr class='" + $$.CLASS.tooltipName + "'>";
text += "<td class='name'>Risk</td>";
text += "<td class='name'>Count</td>";
text += "<td class='value'>Cost</td></tr>";
for (i = 0; i < d.length; i++) {
text += "<tr class='" + $$.CLASS.tooltipName + "'>";
text += "<td class='name'><span style='background-color:"+riskToColor[d[i].name]+"'></span>"+d[i].name+"</td>";
text += "<td class='value'>"+d[i].value+"</td>";
text += "<td class='value'>"+matrix[d[i].x][d[i].name]['cost']+"$</td></tr>";
}
return text + "</table>";
}
}
});
https://codepen.io/georgebuzoianu/pen/djoMKR
您必须建立一个额外的结构来保留整个矩阵(category-cost-count)。使用该矩阵,您将能够为每个计数数据添加相应的成本标签。
答案 1 :(得分:0)
我认为更好的解决方法是使用自定义XY条形图(请参见https://c3js.org/samples/axes_x_tick_format.html)。在这里,您将直接通过c3.js库用数据集定义X轴。
例如,对于您的数据,您可以使用以下自定义X轴:
var chart = c3.generate({
data: {
x: 'cost',
columns: [
['cost', 10, 20, 30, 40, 50, 60],
['count', 30, 200, 100, 400, 150, 250],
],
type: 'bar',
},
});