chart.js - Chart.js 的 y 轴步长从 20 到 1(而不是 1 到 20)
问题描述
我正在使用 chart.js 尝试在此处重新创建此图表:https ://www.transfermarkt.us/fc-liverpool/platzierungen/verein/31
我遇到的问题是让 y 轴从 20 步进到 1。这可能吗?
barChartOptions: ChartOptions = {
responsive: true,
maintainAspectRatio: false,
scales: {
yAxes: [{
ticks: {
reverse: true,
min: 1,
max: 20
}
}]
}
};
不幸的是, reverse: true 属性并不能解决这个问题,因为它也会翻转整个数据。
解决方案
确保不在第一个上显示刻度,yAxis
并添加第二个yAxis
以相反顺序显示生成的刻度。
{
ticks: {
reverse: true,
autoSkip: false,
max: 1,
min: 20
},
afterBuildTicks: (axis, ticks) => Array(20).fill().map((v,i) => i + 1).reverse()
}
此外,您必须定义一个tooltips.callback.label
函数以在工具提示中显示正确的值。
请查看下面的可运行代码片段。
const labels = ['A', 'B', 'C', 'D'];
const data = [12, 1, 8, 17];
const yTop = 1;
const yBottom = 20;
new Chart('myChart', {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: "My Dataset",
data: data.map(v => yBottom + 1 - v),
borderWidth: 3
}]
},
options: {
legend: {
display: false
},
tooltips: {
callbacks: {
label: tooltipItem => data[tooltipItem.index]
}
},
scales: {
yAxes: [{
ticks: {
display: false,
min: yTop,
max: yBottom
},
gridLines: {
drawTicks: false
}
},
{
ticks: {
reverse: true,
autoSkip: false,
max: yTop,
min: yBottom
},
afterBuildTicks: (axis, ticks) => Array(yBottom).fill().map((v, i) => i + 1).reverse()
}
],
xAxes: [{
gridLines: {
display: false
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="120"></canvas>
推荐阅读
- android - 运行 ACTION_RECOGNIZE_SPEECH Intent 时禁用触摸
- javascript - 无法解析 scss react 中的相对 url
- javascript - 使用 Javascript 和 Android Intent 启动 TOMTOM 导航
- progressive-web-apps - 渐进式 Web 应用程序中的脱机身份验证流程
- python - R编程产生错误:原始字段不重复,无法启动列表
- pine-script - 如何设置止损限价入场的时间限制 - TradingView Pine 脚本
- excel - Excel - 每次打印后自动增加多个单元格
- discord.js - 带有斜杠命令的 Discord.js 语音通道
- python - 如何通过python模块获取字典数据?
- python - 使用 PIL 处理图像