图表 js 在顶部显示级别。 (堆叠组的条形图)
Posted
技术标签:
【中文标题】图表 js 在顶部显示级别。 (堆叠组的条形图)【英文标题】:Chart js show levels on top. (Bar chart with Stacked group) 【发布时间】:2021-06-17 18:19:37 【问题描述】:这里我已经实现了基本的堆叠组条形图
其中级别为'Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'
这里有两个堆叠组one, two
<canvas id="myChart"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx,
type: 'bar',
data:
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [
stack: 'one',
label: 'one',
data: [12, 19, 3, 5, 2, 3],
borderWidth: 1
,
stack: 'two',
label: 'two',
data: [19, 3, 5, 2, 3, 12],
borderWidth: 1
,
stack: 'one',
label: 'one',
data: [ 3, 5, 2, 3, 12, 19],
borderWidth: 1
,
stack: 'two',
label: 'two',
data: [ 2, 3, 12, 19, 3, 5],
borderWidth: 1
]
,
options:
scales:
xAxes: [
stacked: true,
],
yAxes: [
stacked: true,
]
);
</script>
输出:
但我想在底部显示堆叠组级别,在贪婪顶部显示数据级别(不是每个条形图)
预期输出:
【问题讨论】:
【参考方案1】:你需要定义一个额外的x轴type: 'category'
如下:
xAxes: [
stacked: true,
position: 'top'
,
type: 'category',
offset: true,
labels: ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']
],
请查看您修改后的可运行代码,看看它是如何工作的:
new Chart('myChart',
type: 'bar',
data:
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [
stack: 'one',
label: 'one',
data: [12, 19, 3, 5, 2, 3],
borderWidth: 1
,
stack: 'two',
label: 'two',
data: [19, 3, 5, 2, 3, 12],
borderWidth: 1
,
stack: 'one',
label: 'one',
data: [3, 5, 2, 3, 12, 19],
borderWidth: 1
,
stack: 'two',
label: 'two',
data: [2, 3, 12, 19, 3, 5],
borderWidth: 1
]
,
options:
legend:
display: false
,
scales:
xAxes: [
stacked: true,
position: 'top'
,
gridLines:
display: false
,
type: 'category',
offset: true,
labels: ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']
],
yAxes: [
stacked: true,
]
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="myChart" ></canvas>
【讨论】:
以上是关于图表 js 在顶部显示级别。 (堆叠组的条形图)的主要内容,如果未能解决你的问题,请参考以下文章