Reputation: 5932
I want to create chart by MPAndroidChart:v3.0.3
so in order to i have implemented it's lib into my gradle.
for practice after initialize chart in my MainActivity class like this:
barChart = findViewById(R.id.chart_report);
barChart.setDrawBarShadow(false);
barChart.setDrawValueAboveBar(true);
barChart.setPinchZoom(false);
barChart.setDrawGridBackground(true);
barChart.setFitBars(true);
I have Setting up chart like this:
ArrayList<BarEntry> barEntries = new ArrayList<>();
barEntries.add(new BarEntry(1, 40f));
barEntries.add(new BarEntry(2, 20f));
barEntries.add(new BarEntry(3, 35f));
barEntries.add(new BarEntry(4, 15f));
BarDataSet barDataSet = new BarDataSet(barEntries, "DataSet1");
barDataSet.setColors(ColorTemplate.COLORFUL_COLORS);
BarData data = new BarData(barDataSet);
data.setBarWidth(0.3f);
barChart.setData(data);
Now everything is ok but i want to change it's XAxis
so in order to i have created a class and implemented IAxisValueFormatter interface like this:
public class ChartAXisValueFormatter implements IAxisValueFormatter {
private String[] mValues;
public ChartAXisValueFormatter(String[] values) {
mValues = values;
}
@Override
public String getFormattedValue(float value, AxisBase axis) {
int val = (int) (value);
String label = "";
if (val >= 0 && val < mValues.length) {
label = mValues[val];
} else {
label = "";
}
return label;
}
}
and use this class like this:
String[] report = new String[]{"A", "B", "C", "D"};
XAxis xAxis = barChart.getXAxis();
xAxis.setValueFormatter(new ChartAXisValueFormatter(report));
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
but as you can see C twice repeated !!! What logic i have to use in getFormattedValue
for avoided this problem ?
Upvotes: 2
Views: 3749
Reputation: 13047
This happens because you have to specify exact number of labels to xAxis:
xAxis.setLabelCount(barEntries.size());
Also see this: https://stackoverflow.com/a/48116532/3101777
Also and a little correction, index should be:
int val = (int) (value) -1;
Upvotes: 6