ValueFormatter at MPAndroidChart repeated twice values


ValueFormatter at MPAndroidChart repeated twice values



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:


MPAndroidChart:v3.0.3


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:


XAxis


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 ?


getFormattedValue



enter image description here




1 Answer
1



This happens because you have to specify exact number of labels to xAxis:


xAxis.setLabelCount(barEntries.size());



enter image description here



Also see this:
https://stackoverflow.com/a/48116532/3101777



Also and a little correction, index should be:


int val = (int) (value) -1;






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

api-platform.com Unable to generate an IRI for the item of type

How to set up datasource with Spring for HikariCP?

PHP contact form sending but not receiving emails