Force BarChart Y axis labels to be integers?

后端 未结 8 753
滥情空心
滥情空心 2021-02-05 11:47

I\'ve created a BarChart using MPAndroidChart and I\'m entering the data dynamically. This means that I need my Y axis to also be determined dynamically. All of my data is repre

8条回答
  •  梦谈多话
    2021-02-05 12:20

    I know that I am answering very late, but I am trying to throw some more light on this issue so that future users have a bit more knowledge regarding the same.

    I also faced the same issue. I used MyYAxisValueFormatter to display only integer value in Y-Axis. Below is the code for the same.

    public class MyYAxisValueFormatter implements YAxisValueFormatter {
    
        private DecimalFormat mFormat;
    
        public MyYAxisValueFormatter () {
            mFormat = new DecimalFormat("###,###,##0");
        }
    
        @Override
        public String getFormattedValue(float value, YAxis yAxis) {
            // write your logic here
            // access the YAxis object to get more information
            return mFormat.format(value);
        }
    }
    

    By using this class what happens is definitely it displays the Y-Axis values in integer format but also duplicate some value. That is because of conversion of float value to integer.

    Let say for example 0.4 will be converted to 0 so there will be two or may be more 0 values in Y-Axis.

    I think this is what happening in case of @Fozefy.

    I implemented below given code to solve this issue and its work like a charm. I used setAxisMaxValue function to set a custom maximum value for Y-axis and setLabelCount to sets the number of label entries for the Y-Axis.

        YAxis yAxis = chart.getAxis(YAxis.AxisDependency.LEFT);
    
        // Minimum section is 1.0f, could be 0.25f for float values
        float labelInterval = 1.0f / 2f;
    
        int sections; //No of sections in Y-Axis, Means your Highest Y-value.
        do {
            labelInterval *= 2; //Interval between labels in Y-Axis
            sections = ((int) Math.ceil(chart.getYMax() / labelInterval));
        } while (sections > 10);
    
        // If the ymax lies on one of the top interval, add another one for some spacing
        if (chart.getYMax() == sections * labelInterval) {
            sections++;
        }
    
        yAxis.setAxisMaximum(labelInterval * sections);
        yAxis.setLabelCount(sections + 1, true);
    

    Label interval remains one if your maximum y-value is less than 10 otherwise two. You can customize this behavior as per your requirement and also increase label interval by modifying do-while loop.

    Also make sure that you are using setLabelCount(int count, boolean force) method and passing force value to true.

提交回复
热议问题