chart.js - Chart.js 将 x 轴标签向右移动
问题描述
我正在使用最新的 chart.js 来绘制一个简单的histogram。直方图很好,但我实际上需要 x 标签位于每个条的边界之间,例如histogram_right_labels,有什么方法可以解决这个问题吗?我试过offsetGridLines: true
and offsetGridLines: false
,但他们实际上做的是移动网格线而不是标签,与我读到的关于他们的实际行为不同,我认为这可能是我的选项设置中的冲突,但我不知道是哪个,任何帮助将不胜感激。
options: {
maintainAspectRatio: false,
layout: {
padding: {
left: 10,
right: 25,
top: 25,
bottom: 0
}
},
scales: {
xAxes: [{
gridLines: {
//display: false,
drawBorder: false,
padding: 20,
offsetGridLines: true
},
ticks: {
beginAtZero: true,
}
}],
yAxes: [{
ticks: {
padding: 10,
},
gridLines: {
color: "rgb(234, 236, 244)",
zeroLineColor: "rgb(234, 236, 244)",
drawBorder: false,
borderDash: [2],
zeroLineBorderDash: [2]
}
}],
},
legend: {
labels: {
boxWidth: 20
},
display: false
},
tooltips: {
backgroundColor: "rgb(255,255,255)",
bodyFontColor: "#858796",
titleMarginBottom: 10,
titleFontColor: '#6e707e',
titleFontSize: 14,
borderColor: '#dddfeb',
borderWidth: 1,
xPadding: 15,
yPadding: 15,
displayColors: false,
intersect: false,
mode: 'index',
caretPadding: 10,
},
}
解决方案
您可以添加第二个 x 轴,type: 'linear'
如下所示。
{
type: 'linear',
ticks: {
min: 0,
max: labels.length,
stepSize: 1,
callback: (v, i) => i == 0 ? '' : labels[i - 1]
}
}
请注意,我使用刻度回调方法来在给定索引处提供所需的刻度标签。
然后您还应该隐藏默认 x 轴的网格线和刻度。
{
gridLines: {
display: false
},
ticks: {
display: false
}
}
请看下面的可运行示例代码,看看它是如何工作的。
const labels = ['4.80', '9.60', '14.40', '19.20', '24.00', '28.80'];
new Chart(document.getElementById('myChart'), {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: "My Dataset",
data: [4, 8, 5, 7, 2, 4],
backgroundColor: 'orange',
categoryPercentage: 1,
barPercentage: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}],
xAxes: [{
gridLines: {
display: false
},
ticks: {
display: false
}
},
{
type: 'linear',
ticks: {
min: 0,
max: labels.length,
stepSize: 1,
callback: (v, i) => i == 0 ? '' : labels[i - 1]
}
}
]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
<canvas id="myChart" height="90"></canvas>
推荐阅读
- laravel - 购物车授权一个月,未授权几个小时 Laravel
- javascript - 使用节点运行编译的 JavaScript 代码时出错
- django - PyTest 案例 1:将以下 UnitTest 代码转换为 PyTest:
- c++ - CreateProcess 的问题和不正确的参数
- c# - Microsoft rate card api 出现损坏。返回部分响应
- android - 在 Android Studio 中使用 Ionic Framework 5.x 在根项目“android”中找不到任务“assembleDebug”
- sapui5 - SAPUI5 计划日历约会在对话框关闭后消失
- javascript - 如何防止代码在 JS 中的 try/catch 失败后执行
- mysql - EntityFramework 存储库,所有行都返回空值
- performance - AMD:TLB 未命中周期的性能计数器