Maxouille
Maxouille

Reputation: 2911

Custom XAxis labels with MPAndroidChart

I'm new with MPAndroidChart and I would like to display time on the XAxis of a LineChart in real time. I wanna display only the 10 last seconds of the incoming data like the image below. My sampling is at 25Hz so I need to display 250 values to have 10 seconds of record.

Something like this

However, I really don't know how to do that. I think I have to use the IAxisValueFormatter.

For the moment, my incoming values are added the the dataset like this :

addEntry(myDataSet, new Entry(myDataSet.getEntryCount(), myNewValue));

but maybe I need to do this :

/* add 40 ms on xAxis for each new value */
addEntry(myDataSet, new Entry(myLastTimeStamp + 40, myNewValue));

and then create a formatter that convert the X values to a string like "xxx seconds" and display only "0s", "5s" and "10s".

I don't know if it works butis there a better way to do this ?

Thx

Upvotes: 1

Views: 6803

Answers (1)

Pavan
Pavan

Reputation: 777

So I see two problems here.
1. You need to plot 250 values in 10 seconds.
2. Formatting the X axis properly.
So the solution for the first problem, you have to display 250 values in ten seconds. So your x Axis effectively will have 250 data points because you are doing :

addEntry(myDataSet, new Entry(myDataSet.getEntryCount(), myNewValue));

So in 1 second you will have 25 points.

Now with all these data let us work on the XAxis.

xAxis = chart.getXAxis();
xAxis.setAxisMinimum(0);
xAxis.setAxisMaximum(250); // because there are 250 data points
xAxis.setLabelCount(3); // if you want to display 0, 5 and 10s which are 3 values then put 3 else whatever of your choice.
xAxis.setValueFormatter(new MyFormatter());

Your formatter then has to look something like this :

public class MyFormatter implements IAxisValueFormatter {
@Override
public String getFormattedValue(float value, AxisBase axis) {
//Modify this as per your needs. If you need 3 values like 0s, 5s and 10s then do this.
//0 mod 125 = 0 Corresponds to 0th second
//125 mod 125 = 0 Corresponds to 5th second
//250 mod 125 = 0 Corresponds to 10th second
    if(value % 125 == 0){
       int second = (int) value / 25; // get second from value
       return second + "s" //make it a string and return
    }else{
       return ""; // return empty for other values where you don't want to print anything on the X Axis
    }
}

Hope this clears everything. Cheers !

Upvotes: 6

Related Questions