Getting duplicate values at xAxis MPChart

倖福魔咒の 提交于 2019-11-30 20:23:09

I was facing the same issue to resolve it add the following line:

xAxis.setGranularityEnabled(true);

Check the link for more details about Axis.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!