How To Set The X-axis Label With Mpandroidchart
I use MPAndroidChart for my app like this: but I can not add tag like that
Solution 1:
Do you need your tag instead of those values?
If so, then here it goes the method to do so.
Add your XAxis
labels to an ArrayList
final ArrayList<String> xLabel = new ArrayList<>();
xLabel.add("9");
xLabel.add("15");
xLabel.add("21");
xLabel.add("27");
xLabel.add("33");
// or use some other logic to save your data in list. For ex. for(i=1; i<50; i+=2)
{
xLabel.add(""+3*i);
}
then use this label in the setValueFormatter
.
Ex:
XAxis xAxis = mChart.getXAxis();
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.setDrawGridLines(false);
xAxis.setValueFormatter(newIAxisValueFormatter() {
@OverridepublicStringgetFormattedValue(float value, AxisBase axis) {
return xLabel.get((int)value);
}
});
Result:
Solution 2:
You can override AxisValueFormatter
i.e.:
xAxis.setValueFormatter(newAxisValueFormatter() {
@OverridepublicStringgetFormattedValue(float value, AxisBase axis) {
return"YOUR_TEXT"; // here you can map your values or pass it as empty string
}
@Overridepublic int getDecimalDigits() {
return0; //show only integer
}
});
You can pick center value of the group to map the group name, others are empty. that would be the easiest way.
Solution 3:
I tried this version: implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0'
:
publicclassBarChartActivity2extendsAppCompatActivity {
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bar_chart2);
BarChartchart= (BarChart) findViewById(R.id.barchart);
int[] numArr = {1, 2, 3, 4, 5, 6};
List<BarEntry> entries = newArrayList<BarEntry>();
for (int num : numArr) {
entries.add(newBarEntry(num, num));
}
BarDataSetdataSet=newBarDataSet(entries, "Numbers");
BarDatadata=newBarData(dataSet);
ValueFormatterxAxisFormatter=newDayAxisValueFormatter(chart);
XAxisxAxis= chart.getXAxis();
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.setDrawGridLines(false);
xAxis.setGranularity(1f); // only intervals of 1 day
xAxis.setLabelCount(7);
xAxis.setValueFormatter(xAxisFormatter);
chart.setData(data);
chart.invalidate();
}
publicclassDayAxisValueFormatterextendsValueFormatter {
privatefinal BarLineChartBase<?> chart;
publicDayAxisValueFormatter(BarLineChartBase<?> chart) {
this.chart = chart;
}
@Overridepublic String getFormattedValue(float value) {
return"your text " + value;
}
}
}
Here is the output:
Solution 4:
I find another solution to this problem. try to add these params
float groupSpace = 0.06f;
float barSpace = 0.02f;
mChart.setData(data);
mChart.groupBars(0f, groupSpace, barSpace);
Post a Comment for "How To Set The X-axis Label With Mpandroidchart"