MPAndroidChart的詳細使用——ValueFormatter和AxisValueFormatter接口的使用

本期是講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 專門用於堆疊柱狀圖。它可以設置繪製所有堆棧值還是隻繪製頂部值。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章