我有一个chart.js折线图,其中x轴标签是普通的旧数字,例如[2,4,15,45,90],代表此图表上的天数。我不希望x轴刻度线反映数据标签,我希望刻度线间隔为20。如何实现此目的?
这在我的选择中什么都不做:
xAxes: [ {
display: true,
position: 'bottom',
ticks: {
stepSize: 20,
min: 0,
max: 140
}
],
此处为示例:jsfiddle
...我发现的唯一(糟糕的)方法是将数字转换为日期,并在ticks回调中计算天数差。如here
您可以使用scatter图表,该图表接受数据作为单个点,即具有属性x
和y
的对象。要将散点图转换为折线图,只需在每个showLine: true
上定义dataset
。
要将产品数据作为单独的点,可以在图表之外定义labels
,并使用Array.map()
如下转换两个值数组。
Array.map()
最后要做的是如下定义valueArray.map((v, i) => ({ x: labels[i], y: v }))
:
xAxis.ticks
请在下面查看您的修改后的代码:
ticks: {
stepSize: 1,
autoSkip: false,
callback: value => value % 20 == 0 ? value : null,
min: labels[0],
max: labels[labels.length - 1],
maxRotation: 0
},
const labels = [7, 14, 21, 35, 42, 49, 56, 63, 70, 77, 84, 91, 98, 105, 119, 126];
var myChart = new Chart('myChart', {
type: 'scatter',
data: {
datasets: [{
label: 'IC',
data: [9432.13209267, 1899.132847, 851.2122668, 3964.48968367, 9433, 8087.04121533, 1268.34642367, 825.29800317, 4271.00722867, 1157.57453933, 4928.214994, 783.88204033, 1846.623016, 4001.84214867, 709.70201067, 3917.61792167, 688.1571182].map((v, i) => ({ x: labels[i], y: v })),
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
showLine: true,
borderWidth: 1
},
{
label: 'Mtb',
data: [14241.41334667, 48348.08833, 5055.28134533, 7614.80689233, 14240, 24536.66203, 1083.99264, 144.72451603, 15968.94539333, 160.150183, 5127.77524033, 953.9963646, 0, 2989.36556, 21.32920023, 27.03159138, 60310.22952333].map((v, i) => ({ x: labels[i], y: v })),
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
showLine: true,
borderWidth: 1
}
]
},
options: {
scales: {
xAxes: [{
display: true,
position: 'bottom',
ticks: {
stepSize: 1,
autoSkip: false,
callback: value => value % 20 == 0 ? value : null,
min: labels[0],
max: labels[labels.length - 1],
maxRotation: 0
},
// afterBuildTicks: (axis, ticks) => [0, 20, 40, 60, 80, 100, 120],
scaleLabel: {
display: true,
labelString: 'Days from initial test',
fontSize: 16
}
}],
yAxes: [{
display: true,
position: 'left',
ticks: {
beginAtZero: true,
stepSize: 10000,
min: 0,
max: 70000
},
scaleLabel: {
display: true,
fontSize: 16
}
},
{
display: true,
position: 'right',
ticks: {
beginAtZero: true,
stepSize: 10000,
min: 0,
max: 70000
},
scaleLabel: {
display: true,
fontSize: 16
}
},
]
}
}
});