我正在使用c3js库来渲染折线图,我想按照这个问题中的要求对x轴类别标签进行分组:c3 js: How can I group by Year on the X-axis labels?。
我尝试过上面的解决方案,但它只适用于系列类型'timeseries'而不适用于'category'。
有点,我找到了使用jQuery的解决方案。以下是代码: var xAxis = ['x', "G1 - Team_1", "G2 - Team_1", "G3 - Team_1", "G4 - Team_1", "G1 - Team_2", "G2 - Team_2", "G3 - Team_2", "G4 - Team_2", "G1 - Team_3", "G2 - Team_3", "G3 - Team_3", "G4 - Team_3", "G1 - Team_4", "G2 - Team_4", "G3 - Team_4", "G4 - Team_4", "G1 - Team_5", "G2 - Team_5", "G3 - Team_5", "G4 - Team_5"],
match1 = ['match1', 32, 4, 2, 46, 24, 54, 18, 65, 87, 25, 3, 6, 16, 63, 46, 62, 69, 37, 50, 65],
match2 = ['match2', 68, 60, 95, 65, 59, 67, 56, 69, 38, 74, 59, 83, 53, 72, 16, 12, 64, 93, 51, 93];
var chart = c3.generate({
data: {
x: 'x',
columns: [xAxis, match1, match2],
type: 'spline',
},
line: {
connectNull: true,
},
axis: {
x: {
label: {
text: 'Group(s)'
},
type: 'category',
tick: {
multiline: true,
centered: true
},
height: 50
}
}
});
//this function changes x-axis labels
function changeXAxisLabel() {
var ticks = $('.c3-axis.c3-axis-x').find('.tick');
var ticksData = ticks.map(function(x, ele) {
return {
text: ele.textContent,
ele: ele,
name: ele.textContent.replace('G1', '')
.replace('G2', '')
.replace('G3', '')
.replace('G4', '')
//.replace('-', '').trim()
};
}).get();
var groupedData = {};
ticksData.forEach(function(ele) {
if (!groupedData[ele.name]) groupedData[ele.name] = [];
groupedData[ele.name].push(ele);
});
Object.keys(groupedData).forEach(function(k) {
if (groupedData[k].length < 2) return;
var addOn = Math.ceil(groupedData[k].length / 2);
var translates = [];
groupedData[k].forEach(function(tick, index) {
var $tick = $(tick.ele);
var val = $tick.attr('transform').replace(/[translate,(),]/g, '').split(' ')[0];
translates.push(Number(val));
$tick.find('tspan:eq(0)').text(tick.text.replace(new RegExp(tick.name, 'i'), '').trim());
$tick.find('tspan:not(:eq(0))').remove();
if (index == addOn) {
var cloned = $tick.clone();
//cloned = cloned.find('line').remove();
var pos = (translates[index] + translates[index - 1]) / 2;
cloned.attr('transform', 'translate(' + pos + ',20)');
cloned.find('tspan').text(tick.name);
cloned.insertAfter($tick);
$(cloned).find('line').remove();
}
})
});
}
首先它显示了所需的结果:
但是在窗口调整大小后,x轴标签会恢复,因为它似乎会重新初始化图表。我试着在window.resize回调上调用changeXAxisLabel:
$(window).resize(function() {
changeXAxisLabel()
})
但它没有按预期运行。它会引发错误:
Error: <g> attribute transform: Expected number, "translate(NaN, 0)".
现在我不明白,这是如何解决的。
如何删除此错误?还是有其他方法可以解决这个问题?
编辑: 以下是此代码示例的jsfiddle:https://jsfiddle.net/abhinaw/1m6v8mwh/
由于
答案 0 :(得分:0)
您可以尝试按以下方式调用您的函数,而不是在$(window).resize()
中进行操作:
var chart = c3.generate({
// just add this function, keep remaining code as it is.
onrendered: function () {
changeRoundChartXAxisLabel();
}
});
这是您JSFiddel的更新版本。
删除了以下代码
$(window).resize(function() {
changeRoundChartXAxisLabel()
})
setTimeout(changeRoundChartXAxisLabel, 100);
但是我无法修复以下错误
Error: <g> attribute transform: Expected number, "translate(NaN, 0)".