使用ChartJS的堆叠式浮动单杠 [英] Stacked Floating Horizontal Bar using ChartJS
问题描述
我正在尝试使用 ChartJS 实现堆叠的水平浮动条,但是我面临着一种异常的行为。有人可以帮忙为什么会这样。我正在使用的代码是:
I am trying to implement Stacked Horizontal Floating Bars using ChartJS but there is an unusual behaviour that I am facing. Can someone please help why is this happening. The code that I am using is :
<html>
<head>
<title>Floating Bars</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<style>
canvas {
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
</style>
</head>
<body>
<div>
<canvas id="canvas" height="100"></canvas>
</div>
<script>
window.onload = function() {
var ctx = document.getElementById('canvas').getContext('2d');
window.myBar = new Chart(ctx, {
type: 'horizontalBar',
data:{
labels:[1],
datasets:[
{
label:'data',
data:[[-3, 5]],
backgroundColor: 'lightblue'
},
{
label:'data',
data:[[6,8]],
backgroundColor: 'lightblue'
},
{
label:'data',
data:[[10, 11]],
backgroundColor: 'lightblue'
}
]
},
options: {
responsive: true,
scales: {
xAxes: [{
stacked : true,
}],
yAxes: [{
stacked : true,
}]
},
legend: {
position: 'top',
},
title: {
display: true,
text: 'Horizontal Floating Bars'
}
}
});
};
</script>
</body>
</html>
以下代码的输出为:
The output of the following code is :
现在,如果将代码与绘制的数据进行比较,我们会看到第一个和第二个数据集,即[-3,5]和[6,8 ]正确绘制,但第三个数据集而不是在[10,11]绘制在[16,17]绘制,即在前面的6上加上10。有人可以解释这个原因吗?
Now if we compare the code with the plotted data we see that the first and the second data set i.e. [-3,5] and [6,8] gets plotted correctly, but the third data set instead of getting plotted at [10,11] gets plotted at [16,17] i.e by adding 10 to the previous 6. Can someone please explain the cause for this?
推荐答案
原因是您正在将值堆叠在 xAxis
上。
The reason is that you're stacking the values on the xAxis
.
只需如下定义xAxis,即可得到预期的结果。
Simply define xAxis as follows and you get the result you're expecting.
xAxes: [{
stacked: false,
}]
window.myBar = new Chart(document.getElementById('canvas'), {
type: 'horizontalBar',
data: {
labels: [1],
datasets: [{
label: 'data 1',
data: [[-3, 5], [6, 8], [10, 11]],
backgroundColor: 'lightblue'
},
{
label: 'data 2',
data: [[6, 8]],
backgroundColor: 'lightblue'
},
{
label: 'data 3',
data: [[10, 11]],
backgroundColor: 'lightblue'
}
]
},
options: {
responsive: true,
scales: {
xAxes: [{
stacked: false,
}],
yAxes: [{
stacked: true,
}]
},
legend: {
position: 'top',
},
title: {
display: true,
text: 'Horizontal Floating Bars'
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="canvas" height="80"></canvas>
这篇关于使用ChartJS的堆叠式浮动单杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!