我正在寻找一种在chart.js
图表上手动指定x / y刻度位置的方法,等效于matplotlib的matplotlib.pyplot.xticks。文档说明了如何create custom tick formats,但是这适用于自动计算的刻度位置。如何指定刻度位置?
这是我正在使用的配置:
var config = {
type: "line",
data: {
labels: [],
datasets: [{
data: [{x: 1, y: 2}, {x: 5, y: 3}, {x: 6, y: 4}],
fill: false,
borderColor: "#1f77b4",
}],
},
options: {
scales: {
xAxes: [{
type: 'linear',
distribution: 'series',
ticks: {
min: 0.,
max: 7.,
},
}]
},
},
}
我想指定xticks的位置,例如[0., 3.5, 5.7, 6.1]
,使绘图看起来更像(不考虑网格线和平滑绘图线):
为了不在图表上绘制网格线,您需要按照Grid Line Configuration的说明在轴上添加以下内容。
gridLines: {
drawOnChartArea: false
}
为了仅在所需位置获得刻度,您将定义如下所示的xAxis.ticks
,并记录在Tick Option和Creating Custom Tick Formats中。
ticks: {
...
stepSize: 0.1,
autoSkip: false,
callback: value => [0, 3.5, 5.7, 6.1].includes(value) ? value : undefined,
maxRotation: 0
},
最后,要获得数据点之间的直线,请按照lineTension: 0
的说明在数据集上定义Line Styling。>
请在下面查看您的修改后的代码。
var config = { type: "line", data: { labels: [], datasets: [{ data: [{x: 1, y: 2}, {x: 5, y: 3}, {x: 6, y: 4}], fill: false, lineTension: 0, borderColor: "#1f77b4", }], }, options: { scales: { xAxes: [{ type: 'linear', ticks: { min: 0., max: 7., stepSize: 0.1, autoSkip: false, callback: value => [0, 3.5, 5.7, 6.1].includes(value) ? value : undefined, maxRotation: 0 }, gridLines: { drawOnChartArea: false } }], yAxes: [{ ticks: { showLabelBackdrop: true }, gridLines: { drawOnChartArea: false } }] }, }, }; new Chart('line-chart', config);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script> <canvas id="line-chart" height="80"></canvas>