brucen
brucen

Reputation: 35

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.

Upvotes: 3

Views: 9212

Answers (2)

Somendra Meena
Somendra Meena

Reputation: 149

You can use IndexAxisValueFormatter for achieving this. Below is the Kotlin example of this.

Create labels arraylist

val labels = arrayListOf<String>("Flue", "Cheese", "...")

Set chart data

val entries = ArrayList<BarEntry>()
// Add entries in the above array list

val dataset = BarDataSet(entries, "Counts")
val barData = BarData(dataset)
chartView.data = barData

Set labels in X Axis

val xAxis = chartView.xAxis
xAxis.position = XAxis.XAxisPosition.BOTTOM
xAxis.setDrawLabels(true)
xAxis.valueFormatter = IndexAxisValueFormatter(labels)

Make sure to call invalidate() at the end.

Upvotes: 0

TR4Android
TR4Android

Reputation: 3246

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.

Upvotes: 4

Related Questions