本期是讲ValueFormatter和AxisValueFormatter 接口的使用
注意:自发布v3.1.0版本以来,不再有任何单独的轴值和图表数据值的格式化程序,它们现在都是ValueFormatter
上一篇:MPAndroidChart的详细使用——设置数据
下一篇:MPAndroidChart的详细使用——图表的一般设置和图表样式设置
ValueFormatter接口
创建一个ValueFormatter(图表和Y轴)
class MyValueFormatter : ValueFormatter() {
private val format = DecimalFormat("###,##0.0")
//折线图 散点图
override fun getPointLabel(entry: Entry?): String {
return format.format(entry?.y)
}
//柱状图
override fun getBarLabel(barEntry: BarEntry?): String {
return format.format(barEntry?.y)
}
// 重写XAxis或yAxis标签的自定义格式设置
override fun getAxisLabel(value: Float, axis: AxisBase?): String {
return format.format(value)
}
//重写其他图表也同理
}
创建一个ValueFormatter(X轴)
下面是格式化一个X轴成为星期的模式
class MyXAxisFormatter : ValueFormatter() {
private val days = arrayOf("Mo", "Tu", "Wed", "Th", "Fr", "Sa", "Su")
override fun getAxisLabel(value: Float, axis: AxisBase?): String {
return days.getOrNull(value.toInt()) ?: value.toString()
}
}
使用
将你格式化的ValueFormatter应用到图表(Data)或者单条线(DataSet),又或者是X轴或者Y轴上
//使用整个数据对象(例如LineData)
lineData.setValueFormatter(MyValueFormatter())
//使用单个DataSet对象(例如LineDataSet)
lineDataSet.valueFormatter = MyValueFormatter()
//X轴
chart.xAxis.valueFormatter = MyXAxisFormatter()
//左Y轴
chart.leftAxis.valueFormatter = MyValueFormatter()
预设格式
LargeValueFormatter | 可用于格式化大值>1000。它将像1000这样的值变成“1k”,1000000将变成“100万”,1000000000将变成“1b” |
---|---|
PercentFormatter | 用于在每个值后面显示一个“%”符号,并以1小数位数显示。特别适用于饼图例如:50变成50.0 % |
StackedValueFormatter | 专门用于堆叠柱状图。它可以设置绘制所有堆栈值还是只绘制顶部值。 |