我们的值在加载站点时可能会有所不同,我们希望动态设置刻度步长。我们在同一图表中有两个具有不同单位的数据集,并希望水平网格线相互匹配。一方面,它是从 0-100% 以 20 为步长的刻度。另一方面,我们希望最大值为 10 的倍数,并将步长设置为最大值的 1/5(因此网格线应相互匹配(。但是,除非修复类型为"10"(参见id:"B"(或类似内容,否则步长将不会加载。我们尝试使用类变量动态设置它,但没有用。我们使用 Angular5 和 ng2-charts 库
public averageOptions: any = {
legend: {
labels: {
fontColor: 'rgb(255,255,255)',
fontSize: 15
}
},
scales: {
yAxes: [{
id: 'A',
type: 'linear',
position: 'left',
ticks: {
min: 0,
max: 100,
stepSize: 20,
fontColor: 'rgb(255,255,255)',
fontSize: 15,
callback: function (value) {
return value + '%';
}
},
gridLines: {
zeroLineColor: 'rgb(255,255,255)',
color: 'rgb(255,255,255)'
}
}, {
id: 'B',
type: 'linear',
position: 'right',
ticks: {
min: this.totalVotesMin,
max: this.totalVotesMax,
fontColor: 'rgb(255,255,255)',
fontSize: 15,
stepSize: 10
},
gridLines: {
zeroLineColor: 'rgb(255,255,255)',
color: 'rgb(255,255,255)'
}
}],
xAxes: [{
ticks: {
fontColor: 'rgb(255,255,255)',
fontSize: 15
},
gridLines: {
zeroLineColor: 'rgb(255,255,255)',
color: 'rgb(255,255,255)'
}
}]
}
};
我们发现了这个有点相关的主题,但我们不知道tick数组的外观或如何设置它,因为没有关于它的文档: 图表.js - 设置最大 Y 轴值并保持步骤正确
这似乎很长,但您可以使用以下代码根据输入数据更改步骤和最大值。
ticks: {
min: 0,
callback: function(value, index, values) {
if (Math.floor(value) === value) {
return value;
}
}
}
public seriesB: Array<number> = [
59.023,
59.023,
59.034,
59.034,
59.034,
59.039,
59.05,
59.061,
59.088,
59.104,
500
];
public lineChartLabels: Array<any> = [
"January",
"February",
"March",
"April",
"May",
"June",
"July"
];
public lineChartOptions: any = {
title: {
display: true,
text: "Line Chart Example"
},
legend: {
position: "bottom"
},
scales: {
yAxes: [`k`
{
id: "SeriesB",
ticks: {
stepSize: 84,
min:0
}
},
]
}
};
public lineChartColors: Array<any> = [
{
backgroundColor: "rgba(255,255,255,0.2)",
borderColor: "rgba(1,1,1)"
}
];
public lineChartData: Array<any> = [
{ data: this.seriesB, label: "SeriesB", yAxisID: "SeriesB" }
];
public lineChartLegend: boolean = true;
public lineChartType: string = "line";
this.lineChartOptions.scales.yAxes[0].ticks.suggestedMin = Math.floor(
Math.min(...this.seriesB)
);
this.lineChartOptions.scales.yAxes[0].ticks.suggestedMax = Math.ceil(
Math.max(...this.seriesB)
);
);