左y轴数值不变,右y轴改成百分比,需要通过自定义RightAxisFormatter实现IAxisValueFormatter接口,将右y轴的数值改成百分比文本,RightAxisFormatter类如下:
TypeScript
class RightAxisFormatter implements IAxisValueFormatter {
maxNumber: number = 0;
constructor(maxNumber: number) {
this.maxNumber = maxNumber;
}
getFormattedValue(value: number, axis: AxisBase): string {
switch (value) {
case this.maxNumber:
return "100%";
case this.maxNumber * 4 / 5:
return "80%";
case this.maxNumber * 3 / 5:
return "60%";
case this.maxNumber * 2 / 5:
return "40%";
case this.maxNumber * 1 / 5:
return "20%";
case 0:
return "0%";
}
return "";
}
}
使用方法如下:
TypeScript
//设置标签文本转换器
rightAxis?.setValueFormatter(new RightAxisFormatter(this.maxNumber));
完整代码如下:
TypeScript
import {
JArrayList,
EntryOhos,
ILineDataSet,
LineData,
LineChart,
LineChartModel,
Mode,
LineDataSet,
XAxisPosition,
IAxisValueFormatter,
AxisBase,
} from '@ohos/mpchart';
class RightAxisFormatter implements IAxisValueFormatter {
maxNumber: number = 0;
constructor(maxNumber: number) {
this.maxNumber = maxNumber;
}
getFormattedValue(value: number, axis: AxisBase): string {
switch (value) {
case this.maxNumber:
return "100%";
case this.maxNumber * 4 / 5:
return "80%";
case this.maxNumber * 3 / 5:
return "60%";
case this.maxNumber * 2 / 5:
return "40%";
case this.maxNumber * 1 / 5:
return "20%";
case 0:
return "0%";
}
return "";
}
}
@Entry
@ComponentV2
struct LeftRightAxisPage {
private model: LineChartModel = new LineChartModel();
minNumber: number = 0;
maxNumber: number = 500;
@Local dataReady: boolean = false;
setData() {
// 创建一个 JArrayList 对象,用于存储 EntryOhos 类型的数据
let values: JArrayList<EntryOhos> = new JArrayList<EntryOhos>();
// 循环生成 1 到 20 的随机数据,并添加到 values 中
for (let i = 1; i <= 20; i++) {
values.add(new EntryOhos(i, Math.random() * 500));
}
// 创建 LineDataSet 对象,使用 values 数据,并设置数据集的名称为 'DataSet'
let dataSet = new LineDataSet(values, 'DataSet');
dataSet.setMode(Mode.CUBIC_BEZIER);
dataSet.setDrawCircles(false);
let dataSetList: JArrayList<ILineDataSet> = new JArrayList<ILineDataSet>();
dataSetList.add(dataSet);
// 创建 LineData 对象,使用 dataSetList数据,并将其传递给model
let lineData: LineData = new LineData(dataSetList);
let leftAxis = this.model.getAxisLeft();
let rightAxis = this.model.getAxisRight();
leftAxis?.setAxisMinimum(this.minNumber);
leftAxis?.setAxisMaximum(this.maxNumber);
//设置有6个标签
leftAxis?.setLabelCount(6, true);
rightAxis?.setAxisMinimum(this.minNumber);
rightAxis?.setAxisMaximum(this.maxNumber);
//设置有6个标签
rightAxis?.setLabelCount(6, true);
//设置标签文本转换器
rightAxis?.setValueFormatter(new RightAxisFormatter(this.maxNumber));
this.model.getXAxis()?.setPosition(XAxisPosition.BOTTOM);
this.model.getDescription()?.setEnabled(false);
this.model?.setData(lineData);
this.dataReady = true;
}
aboutToAppear() {
// 模拟网络请求,延时1秒获取数据
setTimeout(() => {
this.setData()
}, 1000);
}
build() {
Column() {
if (this.dataReady) {
LineChart({ model: this.model })
.width('100%')
.height('50%')
.backgroundColor(Color.White)
} else {
LoadingProgress()
.color(Color.Blue)
}
}
}
}