How to set x axis label using MPAndroidChart

I am using MPAndroidChart for my application like this:

enter image description here

but i cant add a tag like this

+9
android mpandroidchart
source share
4 answers

Do you need a tag instead of these values ?

If so, then there is a way to do this.

Add your XAxis shortcuts to 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 setValueFormatter .
An example :

  XAxis xAxis = mChart.getXAxis(); xAxis.setPosition(XAxis.XAxisPosition.BOTTOM); xAxis.setDrawGridLines(false); xAxis.setValueFormatter(new IAxisValueFormatter() { @Override public String getFormattedValue(float value, AxisBase axis) { return xLabel.get((int)value); } }); 

Result :

enter image description here

+23
source share

You can override AxisValueFormatter

i.e:.

 xAxis.setValueFormatter(new AxisValueFormatter() { @Override public String getFormattedValue(float value, AxisBase axis) { return "YOUR_TEXT"; // here you can map your values or pass it as empty string } @Override public int getDecimalDigits() { return 0; //show only integer } }); 

You can select the central value of the group to match the name of the group, others are empty. that would be the easiest way.

+2
source share

I find another solution to this problem. try adding these parameters

 float groupSpace = 0.06f; float barSpace = 0.02f; mChart.setData(data); mChart.groupBars(0f, groupSpace, barSpace); 
0
source share

I tried this version: implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0' :

 public class BarChartActivity2 extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_bar_chart2); BarChart chart = (BarChart) findViewById(R.id.barchart); int[] numArr = {1, 2, 3, 4, 5, 6}; List<BarEntry> entries = new ArrayList<BarEntry>(); for (int num : numArr) { entries.add(new BarEntry(num, num)); } BarDataSet dataSet = new BarDataSet(entries, "Numbers"); BarData data = new BarData(dataSet); ValueFormatter xAxisFormatter = new DayAxisValueFormatter(chart); XAxis xAxis = 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(); } public class DayAxisValueFormatter extends ValueFormatter { private final BarLineChartBase<?> chart; public DayAxisValueFormatter(BarLineChartBase<?> chart) { this.chart = chart; } @Override public String getFormattedValue(float value) { return "your text " + value; } } } 

Here is the conclusion:

0
source share

All Articles