![](/img/trans.png)
[英]Add Inside Labels to horizontal stacked bar chart chart.js using 'chartjs-plugin-labels'
[英]Stacked Floating Horizontal Bar using ChartJS
我正在嘗試使用ChartJS實現Stacked Horizontal Floating Bars,但我面臨着一種不尋常的行為。 有人可以幫助為什么會發生這種情況。 我使用的代碼是:
<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>
現在,如果我們將代碼與繪制的數據進行比較,我們會看到第一個和第二個數據集,即 [-3,5] 和 [6,8] 被正確繪制,但第三個數據集而不是在 [10, 11] 被繪制在 [16,17] 處,即在前面的 6 上加上 10。有人可以解釋一下原因嗎?
原因是您在xAxis
上堆疊值。
只需按如下方式定義 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.