Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MPandroidChart - zoom in and out to fit values on Y axis only

I am working with the awsome MPandroidChart open-source library and i am populating the chart live from data i am receiving online, when populating the chart with new values, I allow only a specific amount of x index to be visible, using "setVisibleXRange()" and "moveViewToX()" to slide the chart to the left of the screen, displaying only the last entries at a time.

this all works great but I want to achieve a situation where the view port is modified to fit exactly the highest and lowest visible values, same as "fitScreen()" but that modifies the Y axis only. "zoomOut()" and "zoomIn()" are using relative inputs, same as "zoom()" so i cannot use them based on my data. what i need is a way to position the view on the Y axis so the it fits different ranges at each cycle, for example: 2 to 15 or -98 to 34 an so on.

does anyone have any ideas on how this could be done? appreciate all answers. @PhillJay

like image 865
Ziv Kesten Avatar asked Nov 09 '22 13:11

Ziv Kesten


2 Answers

It's a bit old, but to whom it may concern the answer is not about axis. What you need is modifying viewport:

private void autoScaleLineChart(@NonNull LineChart lineChart) {
    if (lineChart.getLineData() == null) return;

    float lowestVisibleX = lineChart.getLowestVisibleX();
    float highestVisibleX = lineChart.getHighestVisibleX();

    LineData chartData = lineChart.getLineData();
    chartData.calcMinMaxY(lowestVisibleX, highestVisibleX);
    //calculating offsets for axes to display correct labels
    lineChart.getXAxis().calculate(chartData.getXMin(), chartData.getXMax());
    calculateMinMaxForYAxis(lineChart, YAxis.AxisDependency.LEFT);
    calculateMinMaxForYAxis(lineChart, YAxis.AxisDependency.RIGHT);
    //this is where the magic happens
    lineChart.calculateOffsets();
    //if nothing happens try adding
    //lineChart.invalidate();
}

private void calculateMinMaxForYAxis(@NonNull LineChart lineChart, @NonNull YAxis.AxisDependency axisDependency) {
    LineData chartData = lineChart.getLineData();
    YAxis yAxis = lineChart.getAxis(axisDependency);
    if (yAxis.isEnabled()) {
        float yMin = chartData.getYMin(axisDependency);
        float yMax = chartData.getYMax(axisDependency);
        yAxis.calculate(yMin, yMax);
    }
}

Also it might be helpful to read this: https://github.com/PhilJay/MPAndroidChart/wiki/Modifying-the-Viewport

like image 162
Михаил Володин Avatar answered Nov 14 '22 23:11

Михаил Володин


Maybe this answer is not perfect, but Yaxis can fit the screen:

chart.getAxisLeft().setLabelCount(10, true);
chart.fitScreen();
like image 33
居然居 Avatar answered Nov 14 '22 21:11

居然居