Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set X axis labels in MP Android Chart (Bar Graph)?

This is with reference to the article : https://github.com/PhilJay/MPAndroidChart/wiki/Setting-Data under the heading Bar Graph.In the given code below:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_graph_test, container, false);

    BarChart chart = view.findViewById(R.id.bar_Chart_test);

    List<BarEntry> entries = new ArrayList<>();
    entries.add(new BarEntry(0f, 30f));
    entries.add(new BarEntry(1f, 80f));
    entries.add(new BarEntry(2f, 60f));
    entries.add(new BarEntry(3f, 50f));
    // gap of 2f
    entries.add(new BarEntry(5f, 70f));
    entries.add(new BarEntry(6f, 60f));

    BarDataSet set = new BarDataSet(entries, "BarDataSet");
    BarData data = new BarData(set);
    data.setBarWidth(0.9f); // set custom bar width
    chart.setData(data);
    chart.setFitBars(true); // make the x-axis fit exactly all bars
    chart.invalidate(); // refresh

    return view;
}

the output was:

Here the X values are not displayed.Click here for the ScreenShot

how to set the X-axis values as months(1st Jan,2nd Jan,3rd Jan.....) as displayed in the article.

like image 574
Shubham Tunwal Avatar asked Dec 04 '17 16:12

Shubham Tunwal


People also ask

How do I label horizontal axis?

Right-click the category labels to change, and click Select Data. In Horizontal (Category) Axis Labels, click Edit. In Axis label range, enter the labels you want to use, separated by commas. For example, type Quarter 1,Quarter 2,Quarter 3,Quarter 4.


1 Answers

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

like image 140
Amir Raza Avatar answered Sep 29 '22 01:09

Amir Raza