BadCash BadCash - 3 months ago 35
Android Question

Can MPAndroidChart automatically convert units?

If I have a

List
of entries in some unit (for example meters) that are being displayed in a MPAndroidChart
LineChart
, is there a way to easily change the unit that the values are being displayed in? Let's say I want to display them in kilometers instead, can MPAndroidChart do the conversion automatically, or do I have to manually create a new
List
of all the entries divided by 1000 and display that instead?

Answer

You can use an IAxisValueFormatter interface to achieve this result. For example, assuming that the values are in meters (m) and you want to display labels in kilometers (km), something like this might work:

public class KilometerValueFormatter implements IAxisValueFormatter {
    @Override
    getFormattedValue(float value, AxisBase axis) {
        int kilometers = (int) value / 1000;
        return kilometers + " km";
    }
}

Then set the KilometerValueFormatter to your axis using:

mChart.getXAxis().setValueFormatter(new KilometerValueFormatter());

Note: starting with version 3.0.0 of this library, the AxisValueFormatter interface has been renamed to IAxisValueFormatter!