Mpandroidchart - Adding Labels to Bar Chart

MPAndroidChart - Adding labels to bar chart

Updated Answer (MPAndroidChart v3.0.1)

Being such a commonly used feature, v3.0.1 of the library added the IndexAxisValueFormatter class exactly for this purpose, so it's just one line of code now:

mBarChart.getXAxis().setValueFormatter(new IndexAxisValueFormatter(labels));

The ProTip from the original answer below still applies.

Original Answer (MPAndroidChart v3.0.0)

With v3.0.0 of the library there is no direct way of setting labels for the bars, but there's a rather decent workaround that uses the ValueFormatter interface.

Create a new formatter like this:

public class LabelFormatter implements IAxisValueFormatter {
private final String[] mLabels;

public LabelFormatter(String[] labels) {
mLabels = labels;
}

@Override
public String getFormattedValue(float value, AxisBase axis) {
return mLabels[(int) value];
}
}

Then set this formatter to your x-axis (assuming you've already created a String[] containing the labels):

mBarChart.getXAxis().setValueFormatter(new LabelFormatter(labels));

ProTip: if you want to remove the extra labels appearing when zooming into the bar chart, you can use the granularity feature:

XAxis xAxis = mBarChart.getXAxis();
xAxis.setGranularity(1f);
xAxis.setGranularityEnabled(true);

MPAndroidChart adding and display bar chart label

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.

adding x-axis labels to mpandroid bar chart shows only the first label in the array list

You don't need following code:

for(int i=0; i<=12;i++){
xAxis.setValueFormatter(new IndexAxisValueFormatter(getXAxisValues().subList(0,i)));
}

All you need is to replace above code with this line:

chart.getXAxis().setValueFormatter(new IndexAxisValueFormatter(getXAxisLables()));

And the method to get labels is:

private ArrayList<String> getXAxisLabels()
{
ArrayList<String> labels = new ArrayList<String> ();

labels.add( "JAN");
labels.add( "FEB");
labels.add( "MAR");
labels.add( "APR");
labels.add( "MAY");
labels.add( "JUN");
return labels;
}

Please modify the getLabels() method in accordance to your requirements.

How to set X axis labels in MP Android Chart (Bar Graph)?

You just make a simple list of string like this :

final ArrayList<String> xAxisLabel = new ArrayList<>();
xAxisLabel.add("Mon");
xAxisLabel.add("Tue");
xAxisLabel.add("Wed");
xAxisLabel.add("Thu");
xAxisLabel.add("Fri");
xAxisLabel.add("Sat");
xAxisLabel.add("Sun");

Then you do this :

    XAxis xAxis = chart.getXAxis();
xAxis.setValueFormatter(new ValueFormatter() {
@Override
public String getFormattedValue(float value, AxisBase axis) {
return xAxisLabel.get((int) value);

}
});

Hope this helps.

set Label in MPAndroid barchart version 3

Use this function--

 public void create_graph(List<String> graph_label, List<Integer> userScore) {

try {
chart.setDrawBarShadow(false);
chart.setDrawValueAboveBar(true);
chart.getDescription().setEnabled(false);
chart.setPinchZoom(false);

chart.setDrawGridBackground(false);

YAxis yAxis = chart.getAxisLeft();
yAxis.setValueFormatter(new IAxisValueFormatter() {
@Override
public String getFormattedValue(float value, AxisBase axis) {
return String.valueOf((int) value);
}
});

yAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);

yAxis.setGranularity(1f);
yAxis.setGranularityEnabled(true);

chart.getAxisRight().setEnabled(false);

XAxis xAxis = chart.getXAxis();
xAxis.setGranularity(1f);
xAxis.setGranularityEnabled(true);
xAxis.setCenterAxisLabels(true);
xAxis.setDrawGridLines(true);

xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.setValueFormatter(new IndexAxisValueFormatter(graph_label));

List<BarEntry> yVals1 = new ArrayList<BarEntry>();

for (int i = 0; i < userScore.size(); i++) {
yVals1.add(new BarEntry(i, userScore.get(i)));
}

BarDataSet set1;

if (chart.getData() != null && chart.getData().getDataSetCount() > 0) {
set1 = (BarDataSet) chart.getData().getDataSetByIndex(0);
set1.setValues(yVals1);
chart.getData().notifyDataChanged();
chart.notifyDataSetChanged();
} else {
// create 2 datasets with different types
set1 = new BarDataSet(yVals1, "SCORE");
set1.setColor(Color.rgb(255, 204, 0));

ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();
dataSets.add(set1);

BarData data = new BarData(dataSets);
chart.setData(data);

}

chart.setFitBars(true);

Legend l = chart.getLegend();
l.setFormSize(12f); // set the size of the legend forms/shapes
l.setForm(Legend.LegendForm.SQUARE); // set what type of form/shape should be used

l.setPosition(Legend.LegendPosition.RIGHT_OF_CHART_INSIDE);
l.setTextSize(10f);
l.setTextColor(Color.BLACK);
l.setXEntrySpace(5f); // set the space between the legend entries on the x-axis
l.setYEntrySpace(5f); // set the space between the legend entries on the y-axis

chart.invalidate();

chart.animateY(2000);

} catch (Exception ignored) {
}
}

And call it on Activity

 BarChart chart;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

chart = (BarChart) findViewById(R.id.barchart);
List<Integer> entries = new ArrayList<>();
entries.add(2000);
entries.add(100);
entries.add(500);
entries.add(250);
entries.add(170);
entries.add(600);

List<String> labels = new ArrayList<>();

labels.add("day1");
labels.add("day2");
labels.add("day3");
labels.add("day4");
labels.add("day5");
labels.add("day6");

create_graph(labels,entries);
}

(MPAndroidChart) Some labels are not showing in Barchart

Finally, found the problem after looking through source code of the library. You should call setLabelCount. After this line:

  XAxis bottomAxis = barChart.getXAxis();

set count to labels of X axis:

   bottomAxis.setLabelCount(entries.size());

And it will work.

Sample Image

Explaination:
Basically, default label count is 6 (if you will not specify) and it doesn't count correctly appropriate labels. In your case you have 5 items, and formatter gets values 0 , 0.8, 1.6, 2.4, 3.2 and 4.0 - 6 values. And this method of the library gives "" value for second value:

   public String getFormattedValue(float value, AxisBase axis) {
int index = Math.round(value);

if (index < 0 || index >= mValueCount || index != (int)value)
return "";

return mValues[index];
}

This is library's source code, that gives you label. And in your case it gives "" when rendering 2nd value.

MPAndroidChart how to display bar color with label bottom of chart in kotlin

That means legend. You can customize it this way

Legend l = chart.getLegend();
l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
l.setDrawInside(false);
l.setForm(LegendForm.SQUARE);
l.setFormSize(9f);
l.setTextSize(11f);
l.setXEntrySpace(4f);

and chart legend enabled:

chart.getLegend().setEnabled(true)

MPAndroidChart Label inside Bar

Try to use:

chart.getXAxis().setPosition(XAxisPosition.BOTTOM_INSIDE);

Or

chart.getXAxis().setPosition(XAxisPosition.TOP_INSIDE);

This will solve your problem.



Related Topics



Leave a reply



Submit