Force BarChart Y axis labels to be integers?

后端 未结 8 745
滥情空心
滥情空心 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:10

    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!

提交回复
热议问题