Search code examples
androidchartsbar-chartmpandroidchartaxis-labels

BarChart X-Value does not correspond with Y-Value


I've got the following BarEntry List:

for (Map.Entry<Date, Float> keyVal : allIncTypesWithAmount.entrySet()) {
    long timeToDays = TimeUnit.MILLISECONDS.toDays(keyVal.getKey().getTime());
    float perDay = timeToDays/30;
    values.add(new BarEntry(perDay,keyVal.getValue()));
}

Which results in following values:

Tue Feb 01 01:00:00 GMT+01:00 2005 value 47.0
Mon Nov 01 01:00:00 GMT+01:00 2021 value 12.0
Mon Apr 01 02:00:00 GMT+02:00 2013 value 76.0
Tue Feb 01 01:00:00 GMT+01:00 2022 value 50.0

My XAxis ValueFormatter:

public class BarChartXAxisValueFormatter extends ValueFormatter 
{

    SimpleDateFormat sdf = new SimpleDateFormat("MM/yyyy", Locale.GERMANY);
    Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    
    @Override
    public String getFormattedValue(float value) {

        float timeToDays = value * 30;
        long emissionsMilliSince1970Time =  TimeUnit.DAYS.toMillis((long) timeToDays) ;
        return sdf.format(getBeginOfMonth(new Date(emissionsMilliSince1970Time)));
    }
    
    
    public static Date getBeginOfMonth(Date d ) {
        calendar.setTime(d);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        return calendar.getTime();
    }

}

The current chart looks like this:

current chart

That's not how I expected it to be.

I'm trying that my chart to look like this:

expected output

Basically, my aim is to ALIGN the X-Value towards the Y-Bar. Of course, if there are many X-Values it wont be possible, but since there are only 4 bars, I want that all 4 X-Value align with the Y-Bar.

Few things I tried:

  • xAxis.setGranularity(1f);
  • setting maxLabelCount

Is there a solution for this?


Solution

  • Use numbers 1,2,3,4,5 etc. as the x value instead of date. Each number should represend a date:

    0 value 47.0
    1 value 12.0
    2 value 76.0
    3 value 50.0
    

    Define the strings, which will be shown for the x value:

    ArrayList<String> xVals = new ArrayList<>();
    xVals.add("04/2020");
    xVals.add("06/2020");
    xVals.add("11/2020");
    xVals.add("01/2021");
    

    Pass the List to the ValueFormatter:

    new ValueFormatter(xVals));
    

    Last but not least, set the granularity:

    xAxis.setGranularity(1f);