[英]Stacked Floating Horizontal Bar using ChartJS
I am trying to implement Stacked Horizontal Floating Bars using ChartJS but there is an unusual behaviour that I am facing.我正在尝试使用ChartJS实现Stacked Horizontal Floating Bars,但我面临着一种不寻常的行为。 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 :以下代码的输出是:
Now if we compare the code with the plotted data we see that the first and the second data set ie [-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] ie by adding 10 to the previous 6. Can someone please explain the cause for this?现在,如果我们将代码与绘制的数据进行比较,我们会看到第一个和第二个数据集,即 [-3,5] 和 [6,8] 被正确绘制,但第三个数据集而不是在 [10, 11] 被绘制在 [16,17] 处,即在前面的 6 上加上 10。有人可以解释一下原因吗?
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.只需按如下方式定义 xAxis,您就会得到您期望的结果。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.