如何在MPAndroidchart中更改Y轴标签的间距?

时间:2017-01-04 16:21:45

标签: android mpandroidchart

如何通过间隙提升YAxis标签,即从给定值开始,如下图所示?如果我尝试使用偏移量,它会使我的YAxis标签值与Y轴数据的绘图不正确。

a stock price line chart with the YAxis labels starting from $412.66

到目前为止,这是我的代码:

  public void setChartProperties() {
        YAxis rightAxis = chart.getAxisRight();
        YAxis leftAxis = chart.getAxisLeft();
        XAxis xAxis = chart.getXAxis();
        chart.getLegend().setEnabled(false);
        chart.getDescription().setEnabled(false);
        chart.setDrawBorders(false);
        chart.setPinchZoom(false);
        chart.setAutoScaleMinMaxEnabled(true);
        chart.setExtraOffsets(0, 0, 0, 0);
        xAxis.setLabelCount(6, true);
        xAxis.setGranularity(1f);
        xAxis.setDrawGridLines(false);
        xAxis.setPosition(XAxisPosition.BOTTOM);
        xAxis.setAvoidFirstLastClipping(true);
        leftAxis.setPosition(YAxisLabelPosition.INSIDE_CHART);
        leftAxis.setDrawLabels(true);
        leftAxis.setSpaceBottom(60);
        leftAxis.setDrawGridLines(true);
        leftAxis.setLabelCount(3, true);
        leftAxis.setCenterAxisLabels(true);
        leftAxis.setDrawGridLines(false);
        rightAxis.setEnabled(false);
        xAxis.setAvoidFirstLastClipping(true);
        dataSet.setColor(R.color.graphLineColor);
    }

这是我的图表的截图。

a chart with the YAxis labels starting from the correct value but with incorrect yValues

1 个答案:

答案 0 :(得分:1)

这是通过实施IAxisValueFormatter来实现的,因为我想保留所有值并只修改标签:

public class MyValueFormatter implements IAxisValueFormatter {

    private final float cutoff;
    private final DecimalFormat format;

    public MyValueFormatter(float cutoff) {
        this.cutoff = cutoff;
        this.format = new DecimalFormat("###,###,###,##0.00");
    }

    @Override
    public String getFormattedValue(float value, AxisBase axis) {
        if (value < cutoff) {
            return "";
        }

        return "$" + format.format(value);
    }
}

然后我用它来消费它:

leftAxis.setValueFormatter(new MyValueFormatter(yMin));

之前定义了yMin

private float yMin = 0; 

然后分配了图表的最小yValue。

a chart with the YAxis labels starting from the minimum yValue as per OP's requirement