How to set X axis labels in MP Android Chart (Bar Graph)?
For the com.github.PhilJay:MPAndroidChart:v3.0.3
I am using a label list:
final List list_x_axis_name = new ArrayList<>();
list_x_axis_name.add("label1");
list_x_axis_name.add("label2");
list_x_axis_name.add("label3");
list_x_axis_name.add("label4");
list_x_axis_name.add("label5");
and setting the label like this:
BarChart chartBar = (BarChart) findViewById(R.id.chartBar);
XAxis xAxis = chartBar.getXAxis();
xAxis.setGranularity(1f);
xAxis.setCenterAxisLabels(true);
xAxis.setLabelRotationAngle(-90);
xAxis.setValueFormatter(new IAxisValueFormatter() {
@override
public String getFormattedValue(float value, AxisBase axis) {
if (value >= 0) {
if (value <= list_x_axis_name.size() - 1) {
return list_x_axis_name.get((int) value);
}
return "";
}
return "";
}
});
You just make a simple list of string like this :
final ArrayList<String> xAxisLabel = new ArrayList<>();
xAxisLabel.add("Mon");
xAxisLabel.add("Tue");
xAxisLabel.add("Wed");
xAxisLabel.add("Thu");
xAxisLabel.add("Fri");
xAxisLabel.add("Sat");
xAxisLabel.add("Sun");
Then you do this :
XAxis xAxis = chart.getXAxis();
xAxis.setValueFormatter(new ValueFormatter() {
@Override
public String getFormattedValue(float value, AxisBase axis) {
return xAxisLabel.get((int) value);
}
});
Hope this helps.
Kotlin:
val xAxisLabels = listOf("1", "2", "3", "4", "5", "6" ...)
barChartView.xAxis.valueFormatter = IndexAxisValueFormatter(xAxisLabels)
Java:
ArrayList<String> xAxisLables = new ArrayList();
xAxisLables.add("1");
xAxisLables.add("2");
xAxisLables.add("3");
xAxisLables.add("4"); ...
OR
String[] xAxisLables = new String[]{"1","2", "3", "4" ...};
barChartView.getXAxis().setValueFormatter(new IndexAxisValueFormatter(xAxisLables));
You can prepare any data you want in xAxisLabels
to display