gpt4 book ai didi

javascript - Chart.js 压缩条形图上的垂直轴

转载 作者:行者123 更新时间:2023-12-01 15:03:53 25 4
gpt4 key购买 nike

我有一个数据集,其中最后一个值总是很高。这导致我的条形图出现问题;如果不将鼠标悬停在它们上面,几乎所有其他值都很难感受。

这是一个屏幕截图:

Example Chart

这就是我想要达到的目标;

Desired Solution

所以我的问题;这在 vanilla Chart.js 中是否可行,还是我需要一个插件?如果是这样;有现成的插件还是我需要自己写一个?

我也对最初问题的替代解决方案持开放态度。

我已经在互联网上到处寻找类似的东西,但不幸的是没有太多运气。

最佳答案

您可以使用 logarithmic类型 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>

关于javascript - Chart.js 压缩条形图上的垂直轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59823030/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com