Getting duplicate values at xAxis MPChart
Setting granularity alone did not solve my problem. Here's what I had to do:
XAxis xAxis = chart.getXAxis();
xAxis.setGranularity(1f);
xAxis.setGranularityEnabled(true);
xAxis.setLabelCount(xLabels.size(),false); // yes, false. This is intentional
xAxis.setValueFormatter(new MyXAxisValueFormatter(xLabels));
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
And, this is my simple implementation of the IAxisValueFormatter
. You may change it as per your needs:
public class MyXAxisValueFormatter implements IAxisValueFormatter {
private ArrayList<String> mValues;
MyXAxisValueFormatter(ArrayList<String> values) {
this.mValues = values;
}
@Override
public String getFormattedValue(float value, AxisBase axis) {
int index = Math.round(value);
if(index >= mValues.size()){
index = mValues.size()-1;
}
return mValues.get(index);
}
}
It's very important to know why every problem occurs and why the solution code solves the problem. So, here's the analysis part:
Why does this occur?
Even in cases where your data lies at whole number positions on the x-axis (0,1,2...), the actual label isn't necessarily placed at those specific positions. For example, the label for the data at 1.00f might be at 0.92f. (This is how the library handles it, not sure why). So, when you try to cast the float value
to an int, you do not get the exact position. From the earlier example, the label at 0.92f when cast to an int would be a 0, not 1.
How does this code solve the problem?
If you understood the above section, then this must not be necessary. Anyways, here's the reasoning. From my test results, I noticed that the label position was at all times nearby the actual x. So, the Math.round()
method was perfect to get the proper index out of the float value.
Additionally, I set the parameter forced
as a false
in the setLabelCount
method because I wanted the labels to hide as the user zooms-in in the x-axis.
I was facing the same issue to resolve it add the following line:
xAxis.setGranularityEnabled(true);
Check the link for more details about Axis.
//set granularity to minimum value to ensure label does not give duplicate value
lineChart.getAxisLeft().setGranularity(1f);
lineChart.getXAxis().setGranularity(1f);
lineChart.getXAxis().setGranularityEnabled(true);
//also make sure you don't pass true as force parameter in below line please pass only false
bottomAxis.setLabelCount(dateLabels.size(),false);