Search code examples
javaandroidandroid-studioandroid-graphview

Android GraphView y-axis not incrementing correctly


I'm currently developing a simple Android app that uses the GraphView library to create a BarGraphSeries and I've noticed a strange occurrence when I'm plotting my data.

I'm returning a count for data that's stored in my local SQLite database and whenever I pass these values to the graphs y-axis the y-axis is incrementing by 0.5 but if I were to hard code the values (for the sake of testing) the y-axis is incrementing by 1 (desired functionality).

Code that's giving me issues:

    // This is how I've declared my variables... I will then go onto call my db
    // and populate each variable with a column count.

    private static int GREAT_COUNT = 0;
    private static int GOOD_COUNT = 0;
    private static int MEH_COUNT = 0;
    private static int FUGLY_COUNT = 0;
    private static int AWFUL_COUNT = 0;

    GraphView graph = findViewById(R.id.graph);
    BarGraphSeries<DataPoint> series = new BarGraphSeries<>(new DataPoint[] {
            new DataPoint(0, GREAT_COUNT),
            new DataPoint(1, GOOD_COUNT),
            new DataPoint(2, MEH_COUNT),
            new DataPoint(3, FUGLY_COUNT),
            new DataPoint(4, AWFUL_COUNT)
    });

Graph generated from passing in a variable to the DataPoint:

Undesired graph

Hard coded values (chart works fine):

    GraphView graph = findViewById(R.id.graph);
    BarGraphSeries<DataPoint> series = new BarGraphSeries<>(new DataPoint[] {
            new DataPoint(0, 2),
            new DataPoint(1, 3),
            new DataPoint(2, 7),
            new DataPoint(3, 10),
            new DataPoint(4, 11)
    });

Graph generated from hard coded values:

Desired graph

I'm new to Android development and I've been doing this to help out a friend for an assignment. Am I doing anything wrong in the declaration of my int variables and this is why it's causing it to increase the y-axis by 0.5 whereas the hard coded values appear to increment as I would have expected in whole numbers.


Solution

  • The y-values of the grid lines are generated automatically depending on minimal and maximal values of the Y-axis and it doesn't matter that you graph values are int. You Y-axis starts with 2 and ends with 4 and there are four "sections". So the lines are set on 2.5, 3.0 and 3.5.

    • You can use setMinY(0) to set zero as starting point for the Y-axis, then you will have grid lines on 1, 2 and 3.
    • You can use setNumVerticalLabels(1) to have only one grid line, it would be on 3 in your case. But note that is your max Y values is 5 , then the grid line would be on 3.5

    Maybe there is a method which allows to set grid lines only on integer values but I didn't find it.