Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to continuously update Y-axis values in MPAndroidChart

I want my axis in LineChart to adjust it's maximum and minimum values real-time. Functions like resetAxisMaxValue() and resetAxisMinValue() work well when new data's Y-value is increasing(both positive and negative), however, once the signal gets low again Y-value max and min never drops to the smaller values so it can show all new data on the full canvas of the graph. I wanted to check whether there is method to do so automatically, or whether I should use brute force. Thank you.

like image 601
Alex Bailo Avatar asked Aug 11 '15 06:08

Alex Bailo


2 Answers

Alex's answer is a bit old, so...

MPAndroidChart has a method called setAutoScaleMinMaxEnabled(boolean enabled). It enables your chart to automatically adjusts the chart's scale. You could use it simply like this.

chart.setAutoScaleMinMaxEnabled(true);
like image 108
DaeYong Kim Avatar answered Nov 01 '22 09:11

DaeYong Kim


I post the solution I have implemented. It works well real time.

Add the following lines to the function where you append data to the graph.

float maxVisiblePoint = -9999999;
float minVisiblePoint = 9999999;

//removing last element from the chart and finding max and min visible value
if(dataSet.getEntryCount() == 650) {
     mChartData.removeXValue(0);
     dataSet.removeEntry(0);

     for (Entry entry : dataSet.getYVals()) {
         if (entry.getVal() > maxVisiblePoint) maxVisiblePoint = entry.getVal();
         if (entry.getVal() < minVisiblePoint) minVisiblePoint = entry.getVal();
         entry.setXIndex(entry.getXIndex() - 1);
     }

//autogain is checked
if (autoScaleChecked) {
    YAxis leftAxis = mChart.getAxisLeft();
    leftAxis.setAxisMaxValue(maxVisiblePoint);
    leftAxis.setAxisMinValue(minVisiblePoint);
}
//static gain
else {
      YAxis leftAxis = mChart.getAxisLeft();
      leftAxis.setAxisMaxValue(5882400f);
      leftAxis.setAxisMinValue(-5882400f);
}
// let the chart know it's data has changed
mChart.notifyDataSetChanged();

Feel free to ask me in case you face some problems. Enjoy!

like image 26
Alex Bailo Avatar answered Nov 01 '22 09:11

Alex Bailo