Chart.js在条形图上压缩垂直轴 [英] Chart.js compress vertical axis on barchart
问题描述
我有一个数据集,其中的最后一个值始终很高.这会导致我的条形图出现问题;如果不将它们悬停在几乎所有其他值上,就很难感觉到.
I have a dataset in which the last value is always very high. This causes an issue with my bar chart; almost all the other values are hard to get a feeling for without hovering over them.
以下是屏幕截图:
这就是我要实现的目标;
This is what I am trying to achieve;
所以我的问题;可以在香草Chart.js中实现此功能,还是需要一个插件?如果是这样;是否有现有的插件,或者我需要自己编写一个插件?
So my question; is this possible within vanilla Chart.js or do I need a plugin? And if so; is there an existing plugin or do I need to write one myself?
我也愿意为最初的问题提供替代解决方案.
I am also open for alternative solutions to the initial problem.
我已经在互联网上寻找了类似的东西,但不幸的是运气不佳.
I've looked all over the internet for something like this but unfortunately without much luck.
推荐答案
您可以使用对数
类型 yAxis
默认值:线性
https://www.chartjs.org/docs/latest/axes/cartesian/logarithmic.html
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["January", "February", "March", "April", "May", "June"],
datasets: [{
label: "Series 1",
backgroundColor: "rgba(255,99,132,0.2)",
borderColor: "rgba(255,99,132,1)",
borderWidth: 2,
hoverBackgroundColor: "rgba(255,99,132,0.4)",
hoverBorderColor: "rgba(255,99,132,1)",
data: [65, 59, 43, 81, 56, 950],
}]
},
options: {
scales: {
yAxes: [{
type: 'logarithmic',
ticks: {
callback: function(tick, index, ticks) {
return tick.toLocaleString();
}
}
}]
}
}
});
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
<canvas id="myChart" width="400" height="200"></canvas>
优化的价格变动
50 * (Math.floor(i / 50)), // lower 50
50 * (Math.ceil(i / 50)) // higer 50
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["January", "February", "March", "April", "May", "June"],
datasets: [{
label: "Series 1",
backgroundColor: "rgba(255,99,132,0.2)",
borderColor: "rgba(255,99,132,1)",
borderWidth: 2,
hoverBackgroundColor: "rgba(255,99,132,0.4)",
hoverBorderColor: "rgba(255,99,132,1)",
data: [65, 59, 43, 81, 56, 950],
}]
},
options: {
scales: {
yAxes: [{
type: 'logarithmic',
ticks: {
callback: function(tick, index, ticks) {
return tick.toLocaleString();
}
},
afterBuildTicks: function(pckBarChart) {
pckBarChart.ticks = pckBarChart.chart.data.datasets[0].data.flatMap(i => [
50 * (Math.floor(i / 50)), // lower 50
50 * (Math.ceil(i / 50)) // higer 50
])
}
}]
}
}
});
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
<canvas id="myChart" width="400" height="200"></canvas>
这篇关于Chart.js在条形图上压缩垂直轴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!