我想绘制一个具有相反条形的图表,如下所示(请忽略黄色部分):
这是我使用 Chart.js 的尝试:
您可以看到有两件事需要修复:
- 蓝色和红色条应该堆叠在一起
- y 轴两端应显示正数
我怎样才能实现这些目标?
最佳答案
您可以使用stacking和 custom ticks功能来产生您想要的结果。
var ctx = document.getElementById('wrapper').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'bar',
// The data for our dataset
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [0, 10, 5, 2, 20, 30, 45],
stack: 'a'
}, {
label: "My Second dataset",
backgroundColor: 'rgb(2, 99, 132)',
borderColor: 'rgb(2, 99, 132)',
data: [-10, -110, -15, -12, -120, -130, -145],
stack: 'b'
}]
},
// Configuration options go here
options: {
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true,
ticks: {
callback: function (value, index, values) {
return value < 0 ? -value : value;
}
}
}]
}
}
});
关于javascript - Chart.js - 绘制具有相反条形的图表 - 如何将 y 轴两端设置为正数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49532701/