BarChart上的Int值

时间:2018-04-27 18:19:26

标签: android android-studio bar-chart mpandroidchart

我希望条形图上的值为整数。我只是设法找出如何使用ValueFormatter修改轴上表示的值,但这不会影响图表上的值。这是我现在拥有的:

enter image description here

这是我的代码:

HorizontalBarChart barChart = findViewById(R.id.bar_chart);

    ArrayList<BarEntry> yValues = new ArrayList<>();
    SharedPreferences appData = getSharedPreferences("app_data", Context.MODE_PRIVATE);
    String[] supermarkets = new String[appData.getAll().size()];
    int i = 0;
    for (Map.Entry<String, ?> entry : appData.getAll().entrySet()) {
        int value = (Integer)entry.getValue();
        BarEntry e = new BarEntry(i, value, 3);
        yValues.add(e);
        supermarkets[i] = entry.getKey();
        i++;
    }

    BarDataSet dataSet = new BarDataSet(yValues, "Supermarkets");
    dataSet.setColors(ColorTemplate.COLORFUL_COLORS);
    BarData data = new BarData(dataSet);

    barChart.getXAxis().setDrawGridLines(false);
    barChart.getXAxis().setDrawAxisLine(false);

    barChart.getAxisLeft().setDrawGridLines(false);
    barChart.getAxisRight().setEnabled(false);
    barChart.getAxisLeft().setEnabled(false);

    barChart.getAxisRight().setDrawGridLines(false);
    barChart.getAxisLeft().setAxisMinimum(0);
    barChart.getAxisRight().setAxisMinimum(0);

    barChart.getXAxis().setValueFormatter(new LabelFormatter(supermarkets));
    barChart.getXAxis().setGranularity(1);
    barChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);

    barChart.setData(data);

public class LabelFormatter implements IAxisValueFormatter {
    private final String[] mLabels;

    LabelFormatter(String[] labels) {
        mLabels = labels;
    }

    @Override
    public String getFormattedValue(float value, AxisBase axis) {
        return mLabels[(int) value];
    }
}

1 个答案:

答案 0 :(得分:1)

您可能希望向YAxis添加ValueFormatter,将值作为字符串返回,如下所示:

barChart.getYAxis().setValueFormatter(new IntegerFormatter());

使用这个简单的类:

public class IntegerFormatter implements IAxisValueFormatter {
    private DecimalFormat mFormat;

    public MyAxisValueFormatter() {
        mFormat = new DecimalFormat("###,###,##0");
    }

    @Override
    public String getFormattedValue(float value, AxisBase axis) {
        return mFormat.format(value);
    }
}

我使用DecimalFormat作为额外的逗号。例如&#34; 1234567&#34;应绘制为&#34; 1,234,567&#34;。有关详细信息,请查看规范hereSource