我正在尝试使用 chart.js 创建混合图表.为了绘图目的,我将数据分成三个不同的数组。示例数据:
labelData:
Ezion Led Light Bulb - Warm White 10.5w E27
Ezion Induction Cooker Ez822
Ezion Led Light Bulb - Daylight 10.5w E27
Ezion Led Light Bulb - Warm White 5.5w E27
Ezion Led Light Bulb - Warm White 7.5w E27
对于 amountData,我希望它采用 horizontalBar 格式。至于数量数据,我希望它采用行格式。
var opt = {
type: "horizontalBar",
data: {
labels: labelData,
datasets: [{
label: brand,
data: amountData,
}, {
type: 'line',
label: brand,
data: quantityData,
}]
},
options: options
};
折线图根本没有绘制。有什么想法吗?
提前致谢!
编辑第 2 部分
这是我尝试填充 labelData 数组的部分。我正在从 firebase 中提取数据,但出于演示目的,我将首先放置一些虚拟数据:
var topProductList = [{itemName: 'Ezion Led Light Bulb - Warm White 10.5w E27'},
{itemName: 'Ezion Induction Cooker Ez822'},
{itemName: 'Ezion Led Light Bulb - Daylight 10.5w E27'},
{itemName: 'Ezion Led Light Bulb - Warm White 5.5w E27'},
{itemName: 'Ezion Led Light Bulb - Warm White 7.5w E27'}];
for(var i = 0 ; i < topProductList.length; i++){
var itemName = topProductList[i].itemName;
itemName = itemName.replace(/\s/g, '\n');
labelData.push(itemName);
}
正如@GRUNT 所建议的,我正在尝试用 '\n' 替换空白区域以正确格式化字符串,以便图表可以执行回调。但是,上面的代码并没有用'\n' 替换空格。这是我得到的:
最佳答案
最简单的解决方法是为工具提示标题使用回调函数(合并标签),例如:
tooltips: {
callbacks: {
title: function(t, d) {
return d.labels[t[0].index].replace(/\n/, ' ');
}
}
}
但首先,您应该使用 x 轴的 ticks 回调函数打破 x 轴标签,而不是使用二维标签数组(如您提到的线程中所建议的那样),就像这样:
xAxes: [{
ticks: {
callback: function(tick) {
return tick.split(/\n/);
}
}
}]
* 在您想要在标签中换行的地方放置一个换行符,例如:Jan\n2017
ᴅᴇᴍᴏ⧩
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: ['Jan\n2017', 'Feb\n2017', 'Mar\n2017', 'Apr\n2017', 'May\n2017'],
datasets: [{
label: 'LINE',
data: [3, 1, 4, 2, 5],
backgroundColor: 'rgba(0, 119, 290, 0.2)',
borderColor: 'rgba(0, 119, 290, 0.6)',
fill: false
}]
},
options: {
scales: {
xAxes: [{
ticks: {
callback: function(tick) {
return tick.split(/\n/);
}
}
}],
yAxes: [{
ticks: {
beginAtZero: true,
stepSize: 1
}
}]
},
tooltips: {
callbacks: {
title: function(t, d) {
return d.labels[t[0].index].replace(/\n/, ' ');
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.0/Chart.min.js"></script>
<canvas id="ctx"></canvas>
关于javascript - chart.js 混合图表中的图表之一未绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46334229/