Prevent repeated y-axis values by controlling granularity

This commit is contained in:
Daniel Cohen Gindi 2016-03-17 16:21:32 +02:00
parent 6347d680c8
commit d430dd61fb
3 changed files with 53 additions and 0 deletions

View file

@ -114,6 +114,7 @@ public class LineChartActivity2 extends DemoBase implements OnSeekBarChangeListe
leftAxis.setAxisMaxValue(200f);
leftAxis.setAxisMinValue(0f);
leftAxis.setDrawGridLines(true);
leftAxis.setGranularityEnabled(true);
YAxis rightAxis = mChart.getAxisRight();
rightAxis.setTypeface(tf);
@ -122,6 +123,7 @@ public class LineChartActivity2 extends DemoBase implements OnSeekBarChangeListe
rightAxis.setAxisMinValue(-200);
rightAxis.setDrawGridLines(false);
rightAxis.setDrawZeroLine(false);
rightAxis.setGranularityEnabled(false);
}
@Override

View file

@ -123,6 +123,19 @@ public class YAxis extends AxisBase {
*/
private AxisDependency mAxisDependency;
/**
* When true, axis labels are controlled by the `granularity` property.
* When false, axis values could possibly be repeated.
* This could happen if two adjacent axis values are rounded to same value.
* If using granularity this could be avoided by having fewer axis values visible.
*/
protected boolean mGranularityEnabled = true;
/**
* the minimum interval between axis values
*/
protected float mGranularity = 1.0f;
/**
* Enum that specifies the axis a DataSet should be plotted against, either LEFT or RIGHT.
*
@ -148,6 +161,36 @@ public class YAxis extends AxisBase {
return mAxisDependency;
}
/**
* @return true if granularity is enabled
*/
public boolean isGranularityEnabled() {
return mGranularityEnabled;
}
/**
* Enabled/disable granularity control on axis value intervals
* @param enabled
*/
public void setGranularityEnabled(boolean enabled) {
mGranularityEnabled = true;
}
/**
* @return the minimum interval between axis values
*/
public float getGranularity() {
return mGranularity;
}
/**
* set the minimum interval between axis values
* @param granularity
*/
public void setGranularity(float granularity) {
mGranularity = granularity;
}
/**
* returns the position of the y-labels
*/

View file

@ -85,8 +85,16 @@ public class YAxisRenderer extends AxisRenderer {
return;
}
// Find out how much spacing (in y value space) between axis values
double rawInterval = range / labelCount;
double interval = Utils.roundToNextSignificant(rawInterval);
// If granularity is enabled, then do not allow the interval to go below specified granularity.
// This is used to avoid repeated values when rounding values for display.
if (mYAxis.isGranularityEnabled())
interval = interval < mYAxis.getGranularity() ? mYAxis.getGranularity() : interval;
// Normalize interval
double intervalMagnitude = Math.pow(10, (int) Math.log10(interval));
int intervalSigDigit = (int) (interval / intervalMagnitude);
if (intervalSigDigit > 5) {