Hot questions for Chart Label in MPAndroidChart

MPCharts add margin to LineDataSet label

Question: I am using MPCharts and cannot figure out how to move the label for the one dataset that I have.

In the screenshot below, I want to move the Time Of Day text about 10dp down so that it is not so close to the x axis. (Not the x axis point labels)

Answer: use setExtraBottomOffset which is by default 15

chart.setExtraBottomOffset(30);

MPandroidchart Pie chart data is not displayed but labels are

Question: I'm trying to implement a simple pie chart using MPAndroidChart, I want the simplest example possible, I want to display it into a fragment, the problem is that the chart is not being redered but the labels are showed in an strange way as we can see in the next screen shot:

This is the code:

class StatsFragment : Fragment() {

    lateinit var debtsChart : PieChart

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val v = inflater.inflate(R.layout.fragment_stats, container, false)

        debtsChart = v.findViewById(R.id.debtsPieChart)

        setupPieChart()

        return v;
    }

    private fun setupPieChart() {
        // Populating a list of PieEntries
        val rainFall : FloatArray = floatArrayOf(98.5f,128.8f,161.6f)
        val monthNames : Array<String> = arrayOf("Jan", "Fab", "Mar")

        val pieEntries = ArrayList<PieEntry>()
        for(a in 1..2){
            pieEntries.add(PieEntry(rainFall[a],monthNames[a]))
        }

        val dataSet = PieDataSet(pieEntries,"Hello world")
        val data = PieData(dataSet)

        debtsChart.data = data
        debtsChart.invalidate()

    }

And this is the xml for the fragment:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorActivityBackground">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:text="@string/detalles_de_deuda_global"
            android:textColor="@android:color/black"
            android:textSize="@dimen/title"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <com.github.mikephil.charting.charts.PieChart
            android:id="@+id/debtsPieChart"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="8dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/textView2" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>

Answer: Just add fillViewPort = "true" to ScrollView to make ConstraintLayout taking all the place on your screen. Cause in the way you made it, the PieChart depends on the sizes of the ConstraintLayout and vice versa. To make everything works properly either must be given a certain height for your chart, or you have to allow ScrollView to take all the place on the screen.

I'd not recommend doing something with a layout in fragment before it is actually created. You can do the same after onViewCreated() is called.


Kotlin: setting custom labels on x axis in line chart Mpandroidchart

Question: i have an arrayList of String with lots of dates, i need put all this dates on the xAxis of my chart create with MPAndroidChart, how can do this i Kotlin?

Here is my code:

 val chart= ChartUtils()
    val mChart:LineChart = root.findViewById(R.id.lineChartEvolCuota) as LineChart

    mChart.isDragEnabled = true
    mChart.setScaleEnabled(false)
    mChart.axisRight.isEnabled=false
    val test : MutableList<object> = db.Object()
    val yArray= ArrayList<Entry>()
    val xLabel  = ArrayList<String>()

    var c = 0f
    for (i in test){
        yArray.add(Entry(c, i.value!!.toFloat()))
        xLabel.add(i.date.toString())
        c+=1f
    }

    val xaxis:XAxis = mChart.xAxis
    xaxis.granularity=1f

    val set1 = LineDataSet(yFondoA, "TEST")
    set1 .color = Color.parseColor(color)
    set1 .setDrawCircles(false)
    set1 .setDrawValues(false)
    val data = LineData(set1)
    mChart.data = data
    mChart.setVisibleXRangeMaximum(365f)
    mChart.moveViewToX(c)

Answer: Using a custom formatter is cleaner than manually setting the labels. Depending on how your dates are extracted from the data you will possibly need to adjust the following line from the example:

val xaxis:XAxis = mChart.xAxis
    xaxis.granularity=1f
    xaxis.setValueFormatter(object : ValueFormatter() {
        val pattern = "dd MMM yy"
        private val mFormat = SimpleDateFormat(pattern)
        private val inputFormat = SimpleDateFormat("yyyy-MM-dd")
        override fun getFormattedValue(value: Float): String {
            val millis = TimeUnit.HOURS.toMillis(value.toLong())
            return mFormat.format(inputFormat.parse(xLabel[value.toInt()]))
        }
    })

Also note that you added your labels to a list but never use them afterwards, which is why you are not seeing them.


MPAndroid Chart not displaying any labels for xAxis , what is missing?

Question: ##########

I'm implementing a feature for displaying Incomes/Expenses for properties & also provided Filter for 1 Month , 3 Months , 6 Months & 12 Months.

So, I have to display Months labels according to filter selected for example if 3 Month filter selected then need to display March , Feb & Jan but what currently labels are not displaying on XAxis

Here is my code , please rectify any issue:

private void setChart() {

    ArrayList<BarEntry> incomeEntries = getIncomeEntries();
    ArrayList<BarEntry> expenseEntries = getExpenseEntries();

    BarDataSet set1, set2;

    set1 = new BarDataSet(incomeEntries, "Income");
    set1.setColor(Color.rgb(65, 168, 121));
    set1.setValueTextColor(Color.rgb(55, 70, 73));
    set1.setValueTextSize(10f);

    set2 = new BarDataSet(expenseEntries, "Expense");
    set2.setColors(Color.rgb(241, 107, 72));
    set2.setValueTextColor(Color.rgb(55, 70, 73));
    set2.setValueTextSize(10f);

    ArrayList<IBarDataSet> dataSets = new ArrayList<>();
    dataSets.add(set1);
    dataSets.add(set2);

    BarData data = new BarData(dataSets);
    barChart.setData(data);


    barChart.getDescription().setEnabled(false);
    barChart.setDrawBarShadow(false);
    barChart.setDrawValueAboveBar(true);
    barChart.setMaxVisibleValueCount(10);
    barChart.setPinchZoom(false);
    barChart.setDrawGridBackground(false);
    barChart.animateY(1400, Easing.EaseInOutQuad);
    barChart.animateXY(3000, 3000);

    Legend l = barChart.getLegend();
    l.setWordWrapEnabled(true);
    l.setTextSize(14);
    l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
    l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
    l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
    l.setDrawInside(false);
    l.setForm(Legend.LegendForm.CIRCLE);


    XAxis xAxis = barChart.getXAxis();
    xAxis.setGranularity(1f);
    xAxis.setCenterAxisLabels(true);
    xAxis.setDrawGridLines(false);
    xAxis.setLabelRotationAngle(-45);
    xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
    xAxis.setAxisMaximum(data.getXMax() + 0.25f);

    ArrayList<String> formatter = getFormattter();

    Log.d(TAG,"Labels Received :"+formatter.size()); // Printing 3

    barChart.getXAxis().setValueFormatter(new IndexAxisValueFormatter(formatter));

    barChart.getXAxis().setLabelCount(formatter.size(),true);

    Log.d(TAG,"Labels Count :"+xAxis.getLabelCount()); // Printing 3

    YAxis leftAxis = barChart.getAxisLeft();
    leftAxis.removeAllLimitLines();
    leftAxis.setTypeface(Typeface.DEFAULT);
    leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
    leftAxis.setTextColor(Color.BLACK);
    leftAxis.setDrawGridLines(false);
    leftAxis.setAxisMinValue(0f); // this replaces setStartAtZero(true
    barChart.getAxisRight().setEnabled(false);

    float maxValue = 0, minValue = 0;

    for (int i = 0; i < incomeEntries.size(); i++) {

        if (maxValue < incomeEntries.get(i).getY()) {
            maxValue = incomeEntries.get(i).getY();
        }

        if (maxValue < expenseEntries.get(i).getY()) {
            maxValue = expenseEntries.get(i).getY();
        }

    }

    maxValue = maxValue + 100;
    Log.e(TAG, "==================== MAX VALUE = " + maxValue);

    leftAxis.setAxisMaximum(maxValue);
    leftAxis.setAxisMinimum(minValue);

    leftAxis.setAxisMaxValue(maxValue);
    leftAxis.setStartAtZero(true);

    data.setValueFormatter(new LargeValueFormatter());

    //data
    float groupSpace = 0.25f;
    float barSpace = 0.05f; // x2 dataset
    float barWidth = 0.35f; // x2 dataset


    barChart.getBarData().setBarWidth(barWidth);
    barChart.getXAxis().setAxisMinValue(10f);
    barChart.groupBars(10, groupSpace, barSpace);
    barChart.invalidate();

}

private ArrayList<String> getFormattter() {

    Log.e(TAG, "GET FORMATTED VALUE");

    switch (chartType) {

        case AppConstants.CHART_TYPE_1_MONTH:
            monthFormatter();
            return oneMonthLabels;

        case AppConstants.CHART_TYPE_3_MONTH:
            threeMonthFormatter();
            return threeMonthLabels;

        case AppConstants.CHART_TYPE_6_MONTH:
            sixMonthFormatter();
            return sixMonthLabels;

        case AppConstants.CHART_TYPE_12_MONTH:
            yearFormatter();
            return yearLabels;
    }
    return null;
}

private void threeMonthFormatter() {

    Log.e(TAG, "threeMonthFormatter , label list size : " + threeMonthLabels.size());
    if (null != threeMonthLabels) {
        threeMonthLabels.clear();
    }

    Calendar calendar = Calendar.getInstance();
    String month = new SimpleDateFormat("MMM").format(calendar.getTime());
    threeMonthLabels.add(month);

    calendar.add(Calendar.MONTH, -1);
    month = new SimpleDateFormat("MMM").format(calendar.getTime());
    threeMonthLabels.add(month);

    calendar.add(Calendar.MONTH, -1);
    month = new SimpleDateFormat("MMM").format(calendar.getTime());
    threeMonthLabels.add(month);

    for (int i = 0; i < threeMonthLabels.size(); i++) {
        Log.e(TAG, "Label : " + threeMonthLabels.get(i));
    }
}

I have attached screen which is achieved as of now.As you can see as per three month Filter , it's displaying bars as per 3 months but there are no labels even monthFormatter create exactly 3 months labels.

Here is another screenshot to display labels received log from Formatter method.

Main Screen

Answer: These two lines are causing the issue :

barChart.getXAxis().setAxisMinValue(10f);     
barChart.groupBars(10, groupSpace, barSpace);

you are setting the minimum value of x axis to 10, whereas the labels will begin with index 0, So internally IndexOut of bound exception keeps occurring So, Change To:

barChart.getXAxis().setAxisMinValue(0f);     // Better remove setAxisMinValue(), as it deprecated
barChart.groupBars(0, groupSpace, barSpace);

If you still want to have 10 as the initial spacing, override IAxisValueFormatter (Not recommended)

barChart.getXAxis().setValueFormatter(new IndexAxisValueFormatter(formatter) {

 @Override
        public String getFormattedValue(float value) {
            int x = (int)value / 10
            if(x > = 0 && x < formatter.size())
               return formatter.get(x);
            else
               return "";
        }
});

As you have fixed group space, bar space and width. you will need to heavily customise for multiple dataset.

I have re-written your solution to adapt to changing width.

BarChart barChart;
ArrayList<IBarDataSet> dataSets = new ArrayList<>();
float defaultBarWidth = -1;
List<String> xAxisValues = new ArrayList<>(Arrays.asList("Jan", "Feb", "March", "April", "May", "June","July", "August", "September", "October", "November", "December"));


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    barChart = findViewById(R.id.barchart);
    setChart(3);
    RadioGroup radioGroup = findViewById(R.id.radio_group);
    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int switchId) {

            switch (switchId) {
                case R.id.one_month:
                    setChart(1);
                    break;
                case R.id.three_month:
                    setChart(3);
                    break;
                case R.id.six_month:
                    setChart(6);
                    break;
                case R.id.tweleve_month:
                    setChart(12);
                    break;
            }
        }
    });
}


private void setChart(int size) {

    List<BarEntry> incomeEntries = getIncomeEntries(size);
    List<BarEntry> expenseEntries = getExpenseEntries(size);
    dataSets = new ArrayList<>();
    BarDataSet set1, set2;

    set1 = new BarDataSet(incomeEntries, "Income");
    set1.setColor(Color.rgb(65, 168, 121));
    set1.setValueTextColor(Color.rgb(55, 70, 73));
    set1.setValueTextSize(10f);

    set2 = new BarDataSet(expenseEntries, "Expense");
    set2.setColors(Color.rgb(241, 107, 72));
    set2.setValueTextColor(Color.rgb(55, 70, 73));
    set2.setValueTextSize(10f);

    dataSets.add(set1);
    dataSets.add(set2);

    BarData data = new BarData(dataSets);
    barChart.setData(data);
    barChart.getAxisLeft().setAxisMinimum(0);

    barChart.getDescription().setEnabled(false);
    barChart.getAxisRight().setAxisMinimum(0);
    barChart.setDrawBarShadow(false);
    barChart.setDrawValueAboveBar(true);
    barChart.setMaxVisibleValueCount(10);
    barChart.setPinchZoom(false);
    barChart.setDrawGridBackground(false);

    Legend l = barChart.getLegend();
    l.setWordWrapEnabled(true);
    l.setTextSize(14);
    l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
    l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
    l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
    l.setDrawInside(false);
    l.setForm(Legend.LegendForm.CIRCLE);

    XAxis xAxis = barChart.getXAxis();
    xAxis.setGranularity(1f);
    xAxis.setCenterAxisLabels(true);
    xAxis.setDrawGridLines(false);
    xAxis.setLabelRotationAngle(-45);
    xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
    xAxis.setAxisMaximum(getExpenseEntries(size).size());

    barChart.getXAxis().setValueFormatter(new IndexAxisValueFormatter(xAxisValues));

    YAxis leftAxis = barChart.getAxisLeft();
    leftAxis.removeAllLimitLines();
    leftAxis.setTypeface(Typeface.DEFAULT);
    leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
    leftAxis.setTextColor(Color.BLACK);
    leftAxis.setDrawGridLines(false);
    barChart.getAxisRight().setEnabled(false);

    setBarWidth(data, size);
    barChart.invalidate();

}

private void setBarWidth(BarData barData, int size) {
    if (dataSets.size() > 1) {
        float barSpace = 0.02f;
        float groupSpace = 0.3f;
        defaultBarWidth = (1 - groupSpace) / dataSets.size() - barSpace;
        if (defaultBarWidth >= 0) {
            barData.setBarWidth(defaultBarWidth);
        } else {
            Toast.makeText(getApplicationContext(), "Default Barwdith " + defaultBarWidth, Toast.LENGTH_SHORT).show();
        }
        int groupCount = getExpenseEntries(size).size();
        if (groupCount != -1) {
            barChart.getXAxis().setAxisMinimum(0);
            barChart.getXAxis().setAxisMaximum(0 + barChart.getBarData().getGroupWidth(groupSpace, barSpace) * groupCount);
            barChart.getXAxis().setCenterAxisLabels(true);
        } else {
            Toast.makeText(getApplicationContext(), "no of bar groups is " + groupCount, Toast.LENGTH_SHORT).show();
        }

        barChart.groupBars(0, groupSpace, barSpace); // perform the "explicit" grouping
        barChart.invalidate();
    }
}

private List<BarEntry> getExpenseEntries(int size) {
    ArrayList<BarEntry> expenseEntries = new ArrayList<>();

    expenseEntries.add(new BarEntry(1,1710));
    expenseEntries.add(new BarEntry(2,2480));
    expenseEntries.add(new BarEntry(3,242));
    expenseEntries.add(new BarEntry(4,2409));
    expenseEntries.add(new BarEntry(5,8100));
    expenseEntries.add(new BarEntry(6,1200));
    expenseEntries.add(new BarEntry(7,6570));
    expenseEntries.add(new BarEntry(8,5455));
    expenseEntries.add(new BarEntry(9,15000));
    expenseEntries.add(new BarEntry(10,11340));
    expenseEntries.add(new BarEntry(11,9100));
    expenseEntries.add(new BarEntry(12,6300));
    return expenseEntries.subList(0, size);
}

private List<BarEntry> getIncomeEntries(int size) {
    ArrayList<BarEntry> incomeEntries = new ArrayList<>();

    incomeEntries.add(new BarEntry(1, 11300));
    incomeEntries.add(new BarEntry(2, 1390));
    incomeEntries.add(new BarEntry(3, 1190));
    incomeEntries.add(new BarEntry(4, 7200));
    incomeEntries.add(new BarEntry(5, 4790));
    incomeEntries.add(new BarEntry(6, 4500));
    incomeEntries.add(new BarEntry(7, 8000));
    incomeEntries.add(new BarEntry(8, 7034));
    incomeEntries.add(new BarEntry(9, 4307));
    incomeEntries.add(new BarEntry(10, 8762));
    incomeEntries.add(new BarEntry(11, 4355));
    incomeEntries.add(new BarEntry(12, 6000));
    return incomeEntries.subList(0, size);
}

Note that the setBarWidth() function is the most important and plays the role of adjusting the width and size of graph bar.


MPAndroidChart - X-axis draw labels only on top

Question: I want to display X-axis labels only on the top of my chart. How can I do it?

I'm using this code:

    XAxis xAxis = chart.getXAxis();
    xAxis.setPosition(XAxis.XAxisPosition.BOTH_SIDED);
    xAxis.setDrawLabels(false);

And this is result:

Or If I do this

    XAxis xAxis = chart.getXAxis();
    xAxis.setPosition(XAxis.XAxisPosition.TOP);
    xAxis.setDrawAxisLine(true);

Then I have labels only on the top BUT the bottom line is missing.

Answer: You want to display xAxis lines for position BOTH_SIDED but without labels on the bottom, so you need to override XAxisRenderer:

    chart.getXAxis().setPosition(XAxis.XAxisPosition.BOTH_SIDED);
    chart.setXAxisRenderer(new XAxisRenderer(chart.getViewPortHandler(), chart.getXAxis(), chart.getTransformer(YAxis.AxisDependency.LEFT)) {
        @Override
        public void renderAxisLabels(Canvas canvas) {
            if (!mXAxis.isEnabled()|| !mXAxis.isDrawLabelsEnabled())
                return;
            MPPointF pointF = MPPointF.getInstance(0f, 0f);
            mAxisLabelPaint.setTypeface(mXAxis.getTypeface());
            mAxisLabelPaint.setTextSize(mXAxis.getTextSize());
            mAxisLabelPaint.setColor(mXAxis.getTextColor());
            pointF.x = 0.5f;
            pointF.y = 1.0f;
            drawLabels(canvas, mViewPortHandler.contentTop() - mXAxis.getYOffset(), pointF);
        }
    });

How to customize chart labels for mpandroidchart library

Question: I'm using the mpandroidchart library for my chart in which I'm showing day's data for a week, 7 days in total.

For each day, I want the label to be the day's name (Sunday, Monday, Tuesday,...). However, label are in numbers (0, 1, 2,...).

How do I customize the labels to show strings rather than ints?

Answer: Use version greater than or equal to 3.0.1 of library and add below lines to your code:

XAxis xAxis = chart.getXAxis();
xAxis.setValueFormatter(new IndexAxisValueFormatter(getXAxisValues()));

Create following method also:

private ArrayList<String> getXAxisValues()
{
    ArrayList<String> labels = new ArrayList<String> ();

    labels.add( "SUN");
    labels.add( "MON");
    labels.add( "TUE");
    labels.add( "WED");
    labels.add( "THU");
    labels.add( "FRI");
    labels.add( "SAT");
    return labels;
}

How to get the width of y-axis label in MPAndroidChart

Question: How to get the width of left y-axis label? or the space between the start of chart and y-axis

Answer: If you would like the get the longest label width then you can do:

chart.getRendererLeftYAxis()
     .getPaintAxisLabels()
     .measureText(chart.getAxisLeft().getLongestLabel())

Or you can get the margins on either side of the labels:

chart.getAxisLeft().getXOffset()

Or you can get the axis width (which are the last two values combined):

chart.getAxisLeft().getRequiredWidthSpace(
    chart.getRendererLeftYAxis().getPaintAxisLabels())

Getting a linechart entry label MPAndroidChart

Question: I have a line chart with entries that the user can click on via line chart.setOnChartValueSelectedListener. Is there a way that I can programmatically get the label of whichever entry is clicked? Or is there some other way of achieving this in my code?

private void chartAreaClickResponse(LineChart lineChart) {
    lineChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
        @Override
        public void onValueSelected(Entry e, Highlight h) {
          //get the label of the entry here

        }

        @Override
        public void onNothingSelected() {

        }
    });
}

Answer: Simply add the following line under "onValueSelected":

    @Override
    public void onValueSelected(Entry e, Highlight h) {
      String label = dataSets.get(h.getDataSetIndex()).getLabel(); //add this
    }

In this case, dataSets is the "ILineDataSet" used to populate the line chart


(MPAndroidChart-LineChart) I didn't get the last label in my app

Question: I use MPAndroidChart v3.0.2 now. The problem is that lasst data('05일') is not showing...

This is the value while I get on Debug xVals : 1일, 2일, 5일

and It is the source and the result screenshot.

I think the '5일' enter the 'red circle'... but I don't know the reason..

  LineChart chart = (LineChart) findViewById(R.id.chart);
    if (ExRegList.length() == 0) {
        chart.clear();
        chart.setDescription(null);
        chart.setNoDataText("데이터가 존재하지 않습니다."); // There is no data.
        chart.invalidate();
    } else {
        ArrayList<Entry> entries = new ArrayList<Entry>();
        final String[] xVals = new String[ExRegList.length()];

        try {
            for (int i = 0; i < ExRegList.length(); i++) {
                JSONObject obj = ExRegList.getJSONObject(i);
                String date = obj.getString("REG_DT").split("-")[2] + "일";
                xVals[i] = date;
                int score = obj.getInt("ANSWER02");
                switch (score) {
                    case 1:
                        entries.add(new Entry(i,3f));//매우만족
                        break;
                    case 2:
                        entries.add(new Entry(i,2f));
                        break;
                    case 3:
                        entries.add(new Entry(i,1f));
                        break;
                    case 4:
                        entries.add(new Entry(i,0f));//매우불만족
                        break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        LineDataSet lineDataSet = new LineDataSet(entries, "");
        lineDataSet.setLineWidth(2);
        lineDataSet.setDrawCircleHole(true);
        lineDataSet.setDrawCircles(true);
        lineDataSet.setDrawHorizontalHighlightIndicator(false);
        lineDataSet.setDrawHighlightIndicators(false);
        lineDataSet.setDrawValues(false);

        LineData lineData = new LineData(lineDataSet);
        chart.setData(lineData);

        XAxis xAxis = chart.getXAxis();
        xAxis.setValueFormatter(new IndexAxisValueFormatter(xVals));
        XAxis bottomAxis = chart.getXAxis();
        bottomAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        bottomAxis.setDrawLabels(true);
        bottomAxis.setDrawGridLines(false);
        bottomAxis.setDrawAxisLine(true);
        bottomAxis.setLabelCount(entries.size());

        YAxis yAxis = chart.getAxisLeft();
        yAxis.setLabelCount(4, true);
        yAxis.setAxisMinimum(0.0f);
        yAxis.setAxisMaximum(3.0f);

        yAxis.setValueFormatter(new IAxisValueFormatter() {

            @Override
            public String getFormattedValue(float value, AxisBase yAxis) {
                String format = "";
                switch ((int) value) {
                    case 3:
                        format = "매우 만족";
                        break;
                    case 2:
                        format = "만족";
                        break;
                    case 1:
                        format = "불만족";
                        break;
                    case 0:
                        format = "매우 불만족";
                        break;
                    default:
                        break;
                }
                return format;
            }
        });
        yAxis.setTextColor(Color.BLACK);

        YAxis yRAxis = chart.getAxisRight();
        yRAxis.setDrawLabels(false);
        yRAxis.setDrawAxisLine(false);
        yRAxis.setDrawGridLines(false);

        chart.setFocusable(false);
        chart.setPinchZoom(false);
        chart.setDoubleTapToZoomEnabled(false);
        chart.setDrawGridBackground(false);
        chart.setDescription(null);
        chart.getLegend().setEnabled(false);
        chart.animateY(2000, Easing.EasingOption.EaseInCubic);
        chart.invalidate();

Answer: Instead of this:

bottomAxis.setLabelCount(entries.size());

Use this overloaded version:

bottomAxis.setLabelCount(entries.size(), true);

Second parameter, boolean force forces to have exact number of labels. Without it, sometimes the method doesn't work, like in your case. From source code you can see:

sets the number of label entries for the y-axis max = 25, min = 2, default: 6, be aware that this number is not fixed (if force == false) and can only be approximated.

(MPAndroidChart) Some labels are not showing in Barchart

Question: I'm using MPAndroidChart

I made one barchart, but xAxis-2nd value is not showing./p>

x,y : 1 week, 3회

x,y : 2 week, 0회

x,y : 3 week, 0회

x,y : 4 week, 0회

x,y : 5 week, 0회

Those are my entry values. But like this, 2nd label is not showing in my phone.

I attached source and result screenshot.

ArrayList<BarEntry> entries = new ArrayList<>();
        ArrayList<String> labels = new ArrayList<String>();
        String[] labels2 = new String[ExRegList.length()];
        try {
            exerciseWholeCnt = ExRegList.length();
            for (int i = 0; i < ExRegList.length(); i++) {
                JSONObject obj = ExRegList.getJSONObject(i);
                String week = obj.getString("WEEK");
                int exCnt = obj.getInt("RESULT_COUNT");
                labels.add(week + "주");
                labels2[i] = week+"주";
                entries.add(new BarEntry(i,exCnt));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        XAxis xAxis = barChart.getXAxis();
        xAxis.setValueFormatter(new IndexAxisValueFormatter(labels2));
        XAxis bottomAxis = barChart.getXAxis();
        bottomAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        bottomAxis.setDrawLabels(true);
        bottomAxis.setDrawGridLines(false);
        bottomAxis.setDrawAxisLine(true);



        YAxis left = barChart.getAxisLeft();
        left.setAxisMinimum(0);
        left.setAxisMaximum(7);

        BarDataSet barDataSet = new BarDataSet(entries, "01");
        BarData barData = new BarData(barDataSet);

        YAxis rightYAxis = barChart.getAxisRight();
        rightYAxis.setEnabled(false);

        barChart.setData(barData);
        barChart.setDescription(null);
        barChart.setPinchZoom(false);
        barChart.setScaleEnabled(false);
        barChart.setDrawBarShadow(false);
        barChart.setDrawGridBackground(false);
        barChart.animateY(2000);
        barChart.getLegend().setEnabled(false);
        barChart.getData().setValueTextSize(10);

        barChart.getBarData().setValueFormatter(new IValueFormatter() {
            @Override
            public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                if (value != 0) {
                    DecimalFormat format = new DecimalFormat("#");
                    return format.format(value) + "회";
                }
                return "";
            }
        });

//            barChart.getXAxis().setValueFormatter(new MyValueFormatter());

        barChart.invalidate();
    }

and the result is.

Answer: Finally, found the problem after looking through source code of the library. You should call setLabelCount. After this line:

  XAxis bottomAxis = barChart.getXAxis();

set count to labels of X axis:

  bottomAxis.setLabelCount(entries.size());

And it will work.

Basically, default label count is 6 (if you will not specify) and it doesn't count correctly appropriate labels. In your case you have 5 items, and formatter gets values 0 , 0.8, 1.6, 2.4, 3.2 and 4.0 - 6 values. And this method of the library gives "" value for second value:

   public String getFormattedValue(float value, AxisBase axis) {
        int index = Math.round(value);

        if (index < 0 || index >= mValueCount || index != (int)value)
            return "";

        return mValues[index];
    }

This is library's source code, that gives you label. And in your case it gives "" when rendering 2nd value.


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

Question: 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;
}

Here the X values are not displayed.

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

Answer: 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 = mBarChart.getXAxis();
xAxis.setValueFormatter(new IAxisValueFormatter() 
@Override
public String getFormattedValue(float value, AxisBase axis) {
    return xAxisLabel.get((int) value);
      }
 });

Remove Y label on point

Question: How to remove the Y value on the circle point? Or just change the color to white.

val lineData = LineData(dataSet)
        chart.setNoDataText("Nenhum treino computado")
        chart.setDrawBorders(false)
        chart.data = lineData
        chart.description = desc
        chart.setGridBackgroundColor(R.color.graphGride)
        chart.setDrawGridBackground(false)
        chart.legend.textColor = ActivityCompat.getColor(this, R.color.graphLabel)
        chart.axisLeft.gridColor = ActivityCompat.getColor(this, R.color.graphLabel)
        chart.xAxis.position = XAxis.XAxisPosition.BOTTOM
        chart.xAxis.textColor = ActivityCompat.getColor(this, R.color.graphLabel)
        chart.xAxis.axisLineColor = ActivityCompat.getColor(this, R.color.graphLabel)
        chart.xAxis.setCenterAxisLabels(true)

Answer: To remove the values :

dataSet.setDrawValues(false);

To change the color :

dataSet.setValueTextColor(Color.WHITE);