我希望条形图上的值是整数。我只设法找出如何使用 ValueFormatter 修改轴上表示的值,但这并不影响图表上的值。这是我目前拥有的:
这是我的代码:
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];
}
}
最佳答案
您可能想向 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 用于额外的逗号。例如“1234567”应该画成“1,234,567”。有关详细信息,请查看规范 here 。 Source
关于android - BarChart 上的 Int 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50068159/