Force BarChart Y axis labels to be integers?
Allright, now I see your problem.
THe problem is that the YAxis
(YLabels) determines the number of digits and thus the steps between each label automatically.
Unfortunately it's currently not possible to customize how the axis computes itself or set custom labels.
I am considering to add such a feature in the future, where the user can self define which values are drawn as the axis labels.
Just a hint:
The mEntries
array that holds all the axis labels is public. So in general, you could modify it after it has been created.
However, I am absolutely not sure how the axis will behave if you manually modify it.
But maybe its worth a try :-) https://github.com/PhilJay/MPAndroidChart/blob/master/MPChartLib/src/com/github/mikephil/charting/components/YAxis.java
Pretty simple. All you need is two things:
Axis value formatter
mChart.getAxisLeft().setValueFormatter(new ValueFormatter() { @Override public String getFormattedValue(float value) { return String.valueOf((int) Math.floor(value)); } });
Axis label count
int max = findMaxYValue(yourdata); // figure out the max value in your dataset mChart.getAxisLeft().setLabelCount(max);
This is how I resolved this issue. It seems like the y axis is always drawn 1 over the max value(if its not force it). So set the label count 2 over the max value(include zero and one over your max) then all you need to do is remove the decimal with the axis formatter. This works if all your y values are integers, not sure how it would work with decimal values.
barChart.getAxisLeft().setLabelCount(maxYvalue + 2, true);
barChart.getAxisLeft().setAxisMinValue(0f);
barChart.getAxisLeft().setAxisMaxValue(maxYvalue + 1);
YAxisValueFormatter customYaxisFormatter = new YAxisValueFormatter() {
@Override
public String getFormattedValue(float value, YAxis yAxis) {
return String.valueOf((int)value);
}
};
barChart.getAxisLeft().setValueFormatter(customYaxisFormatter);
After looking around with no solution available, I've decided to look into the javadoc and found out about this method: setGranularity(float)
. To force the YAxis to always display integers (or any interval you want), you just need to call this:
yAxisLeft.setGranularity(1.0f);
yAxisLeft.setGranularityEnabled(true); // Required to enable granularity
However, if the min and max values of the chart is too close, then the chart will not honor setLabelCount()
, unless when is forced (which will make the labels in decimal again), so you need to call this after setting data:
private void calculateMinMax(BarLineChartBase chart, int labelCount) {
float maxValue = chart.getData().getYMax();
float minValue = chart.getData().getYMin();
if ((maxValue - minValue) < labelCount) {
float diff = labelCount - (maxValue - minValue);
maxValue = maxValue + diff;
chart.getAxisLeft().setAxisMaximum(maxValue);
chart.getAxisLeft().setAxisMinimum(minValue);
}
}
And that's it!