Skip to content

The AxisValueFormatter interface

Philipp Jahoda edited this page Aug 6, 2016 · 18 revisions

Introduced in release v3.0.0, this interface allows the custom styling of both XAxis and YAxis values before drawing.

###Creating a Formatter

All that needs to be done to custom-format values on the axis is to create a class that implements the AxisValueFormatter interface, as shown below. This formatter is used to format the values of an axis to 1 decimal digit always.

public class MyYAxisValueFormatter implements AxisValueFormatter {

    private DecimalFormat mFormat;

    public MyAxisValueFormatter() {

        // format values to 1 decimal digit
        mFormat = new DecimalFormat("###,###,###,##0.0");
    }

    @Override
    public String getFormattedValue(float value, AxisBase axis) {
        // "value" represents the position of the label on the axis (x or y)
        return mFormat.format(value) + " $";
    }
    
    /** this is only needed if numbers are returned, else return 0 */
    @Override
    public int getDecimalDigits() { return 1; }
}

The example below shows how to plot values from a String[] array to the axis:

public class MyXAxisValueFormatter implements AxisValueFormatter {

    private String[] mValues;

    public MyXAxisValueFormatter(String[] values) {
        this.mValues = values;
    }

    @Override
    public String getFormattedValue(float value, AxisBase axis) {
        // "value" represents the position of the label on the axis (x or y)
        return mValues[(int) value];
    }
    
    /** this is only needed if numbers are returned, else return 0 */
    @Override
    public int getDecimalDigits() { return 0; }
}

###Setting the Formatter

After the creation of the formatter, simply set it to your axis of choice:

YAxis left = chart.getAxisLeft();
left.setValueFormatter(new MyYAxisValueFormatter());

XAxis xAxis = chart.getXAxis();
xAxis.setValueFormatter(new MyXAxisValueFormatter());

Instead of the default values ranging from axis minimum value to axis maximum value, the axis will now plot the data specified by the formatter.

###Legacy Formatters

Prior to release v3.0.0, there were separate formatters for XAxis and YAxis. The documentation for these formatters can be found here:

The documentation has moved.

Clone this wiki locally