androidmpandroidchart

MPAndroidChart adding and display bar chart label


Just started using the MPAndroidChart version 3.0.0 beta and i have created a project that can show my values in a bar chart. My question is where do i add and display labels. Each Bar should have its own label eg. "Flue", "Cheese" etc at the bottom. Not sure what function does this, am actively searching and reading the Docs/Wiki but no joy currently.


Solution

  • Depending on your preferences, you can use the data property of an Entry to store the label and then return it in your IAxisValueFormatter implementation:

    public class LabelValueFormatter implements IAxisValueFormatter {
        private final DataSet mData;
    
        public LabelValueFormatter(DataSet data) {
            mData = data;
        }
    
        @Override
        public String getFormattedValue(float value, AxisBase axis) {
            // return the entry's data which represents the label
            return (String) mData.getEntryForXPos(value, DataSet.Rounding.CLOSEST).getData();
        }
    }
    

    This approach allows you to use the Entry constructor (or BarEntry in this case) to add the labels, which can improve the readability of your code:

    ArrayList<BarEntry> entries = new ArrayList<>();
    for (int i = 0; i < length; i++) {
        // retrieve x-value, y-value and label
        entries.add(new BarEntry(x, y, label));
    }
    BarDataSet dataSet = new BarDataSet(entries, "description");
    BarData data = new BarData(dataSet);
    mBarChart.setData(data);
    mBarChart.getXAxis().setValueFormatter(new LabelValueFormatter(data));
    

    Also check out this answer for more information and an alternative approach on using labels with the BarChart and the new 3.0.0 version of the library.