Hot questions for Pie Chart in MPAndroidChart

adding values to Pie Chart programmatically android

Question: I am using MP android Pie Chart API to generate a pie chart for my android app. I followed one youtube tutorial to add details statically to the Pie chart and It got successfully added The code:

public class EnergyBreakdown extends AppCompatActivity {
    PieChart pieChart;
    ArrayList<PieEntry> entries;
    ArrayList<String> PieEntryLabels;
    PieDataSet pieDataSet;
    PieData pieData;
    int LightDimmerLevel =2;
    int NumberofLights=5;
    int result;
    ArrayList<Integer> lightResult;

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

        pieChart=findViewById(R.id.piechart);
        entries=new ArrayList<>();
        PieEntryLabels = new ArrayList<String>();

        AddValuesToPIEENTRY();

        AddValuesToPieEntryLabels();

        pieDataSet = new PieDataSet(entries, "");

        pieData = new PieData(pieDataSet);

        pieDataSet.setColors(ColorTemplate.COLORFUL_COLORS);

        pieChart.setData(pieData);
        pieChart.setCenterText("Energy Breakdown");

        pieChart.animateY(3000);

    }
    public void AddValuesToPIEENTRY(){

        entries.add(new PieEntry(2f, 0));
        entries.add(new PieEntry(4f, 1));
        entries.add(new PieEntry(6f, 2));
        entries.add(new PieEntry(8f, 3));
        entries.add(new PieEntry(7f, 4));
        entries.add(new PieEntry(3f, 5));

    }

    public void AddValuesToPieEntryLabels(){

        PieEntryLabels.add("January");
        PieEntryLabels.add("February");
        PieEntryLabels.add("March");
        PieEntryLabels.add("April");
        PieEntryLabels.add("May");
        PieEntryLabels.add("June");
    }
}

I got result like this

But now I want to add it dynamically as in make some calculation and add data to pie chart. I made some changes in the code but it is not showing any data

public class EnergyBreakdown extends AppCompatActivity {
    PieChart pieChart;
    ArrayList<PieEntry> entries;
    ArrayList<String> PieEntryLabels;
    PieDataSet pieDataSet;
    PieData pieData;
    int LightDimmerLevel =2;
    int NumberofLights=2;
    int result;
    ArrayList<Integer> lightResult;

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

        pieChart=findViewById(R.id.piechart);
        entries=new ArrayList<>();
        PieEntryLabels = new ArrayList<String>();

        AddValuesToPIEENTRY();

        AddValuesToPieEntryLabels();

        pieDataSet = new PieDataSet(entries, "");

        pieData = new PieData(pieDataSet);

        pieDataSet.setColors(ColorTemplate.COLORFUL_COLORS);

        pieChart.setData(pieData);
        pieChart.setCenterText("Energy Breakdown");

        pieChart.animateY(3000);

    }
    public void AddValuesToPIEENTRY(){
        for (int i=0;i<NumberofLights+1;i++){
            result=((LightDimmerLevel)/(NumberofLights*5))*100;

            entries.add(new PieEntry(result));
        }
//       
    }

    public void AddValuesToPieEntryLabels(){

        PieEntryLabels.add("January");
        PieEntryLabels.add("February");
        PieEntryLabels.add("March");
        PieEntryLabels.add("April");
        PieEntryLabels.add("May");
        PieEntryLabels.add("June");
    }
}

Can anyone help where I am doing wrong and where should i make changes to add data dynamically to pie chart dynamically

Answer: By looking your static data, it needs to pass float type data, change your int variable to float and the second param is index of loop

float LightDimmerLevel = 2;
float NumberofLights = 2;
float result;

...

public void AddValuesToPIEENTRY(){
     for (int i=0;i<NumberofLights+1;i++){
        result=((LightDimmerLevel)/(NumberofLights*5))*100;
        entries.add(new PieEntry(result, i));
     }     
}

How to remove bottom space in a pie chart?

Question: I am using Pie Chart in my application, Right now Pie Chart is displaying properly ,only issue is getting space at bottom of Pie Chart. Following is code of Pie Chart and output what I want and What I am trying to get.

PieChart pieChart = (PieChart) view.findViewById(R.id.fragment_chart);
        pieChart.setUsePercentValues(true);
        Display display = getActivity().getWindowManager().getDefaultDisplay();
        int height = display.getHeight();  // deprecated

        int offset = (int)(height * 0.65); /* percent to move */

       /* RelativeLayout.LayoutParams rlParams =
                (RelativeLayout.LayoutParams)pieChart.getLayoutParams();
        rlParams.setMargins(0, 0, 0, -offset);
        pieChart.setLayoutParams(rlParams);*/
        // IMPORTANT: In a PieChart, no values (Entry) should have the same
        // xIndex (even if from different DataSets), since no values can be
        // drawn above each other.
        ArrayList<PieEntry> yvalues = new ArrayList<PieEntry>();
        yvalues.add(new PieEntry(8f, 0));
        yvalues.add(new PieEntry(15f, 1));
        yvalues.add(new PieEntry(12f, 2));


        PieDataSet dataSet = new PieDataSet(yvalues, "Reward Points");

        ArrayList<String> xVals = new ArrayList<String>();

        xVals.add("January");
        xVals.add("February");
        xVals.add("March");
        xVals.add("April");
        xVals.add("May");
        xVals.add("June");

        PieData data = new PieData( dataSet);

        data.setValueFormatter(new PercentFormatter());
        pieChart.setData(data);
        //pieChart.setDescription("This is Pie Chart");

        pieChart.setBackgroundColor(Color.TRANSPARENT);
        pieChart.setHoleColor(Color.WHITE);
        pieChart.setTransparentCircleColor(Color.WHITE);
        pieChart.setTransparentCircleAlpha(0);
        pieChart.setHoleRadius(18f);
        pieChart.setDrawCenterText(true);
        pieChart.isRotationEnabled();
        pieChart.isHighlightPerTapEnabled();
        pieChart.setCenterTextOffset(0f,-20f);
        pieChart.setEntryLabelColor(Color.WHITE);
        pieChart.setEntryLabelTypeface(Typeface.DEFAULT);
        pieChart.setEntryLabelTextSize(16f);
        pieChart.setTransparentCircleRadius(11f);

        pieChart.setDrawHoleEnabled(true);


        pieChart.setMaxAngle(180.0f);
        pieChart.setRotationAngle(180.0f);
        pieChart.setCenterTextSize(30);

        dataSet.setColors(ColorTemplate.VORDIPLOM_COLORS);
        data.setValueTextSize(13f);

        data.setValueTextColor(Color.DKGRAY);
        //pieChart.setOnChartValueSelectedListener(getActivity());

        pieChart.animateY(1400, Easing.EaseInOutQuad);

Expected Output

Getting Output

Answer: Use below code.

pieChart.setHoleRadius(64f);//18f
pieChart.setCenterTextSize(10);//30
pieChart.setCenterText("Reward Points: 150");//new line

pieChart.setExtraOffsets(5f,0f,10f,-100f);

Adjust value of bottom offset in setExtraOffsets(in above code value -100f) in order to adjust space.


Android MPAndroidChart Text Overlapping with PieChart

Question: I am using MPAndroidChart for showing values in PieChart.

I'm not clear to fix text overlapping in PieChart Below image am getting as result.

The orange value contains 3, it showing at bottom, but green value contains 2, it not showing up properly. Solution needs for green value.

    chart.setUsePercentValues(false);
    chart.getDescription().setEnabled(false);
    chart.getDescription().setTextSize(25f);
    chart.setExtraOffsets(5, 5, 5, 5);
    chart.getLegend().setEnabled(false);

    chart.setDragDecelerationFrictionCoef(0.95f);

    chart.setCenterTextTypeface(tfLight);
    chart.setCenterTextColor(getResources().getColor(R.color.white));

    chart.setDrawHoleEnabled(true);
    chart.setHoleColor(getResources().getColor(R.color.toolBar));

    chart.setTransparentCircleColor(R.color.toolBar);
    chart.setTransparentCircleAlpha(110);

    chart.setHoleRadius(35f);
    //  chart.setTransparentCircleRadius(61f);
    chart.getXAxis().setTextColor(Color.WHITE);
    chart.setDrawCenterText(true);

    chart.setRotationAngle(0);
    // enable rotation of the chart by touch
    chart.setRotationEnabled(false);
    chart.setHighlightPerTapEnabled(true);

Can Anyone help me out from this issue, where my code went wrong?

Answer: adding below lines to avoid overlapping text with pieChart

PieData data = new PieData(dataSet);
dataSet.setValueLinePart1OffsetPercentage(90.f); 
dataSet.setValueLinePart1Length(.10f);
dataSet.setValueLinePart2Length(.50f);

Ho to set MPAndroid piechart no lable

Question: I'v used MPAndroid PieChart and want to show only percent values without labels. When I remove labels then colored guide below of chart also is without label. How to remove labels from pichart without removing guide labels?

Answer: set setDrawLabels(false) for the axis.

setDrawLabels(boolean enabled): Set this to true to enable drawing the labels of the axis.


manage text in some Situation PieChart of MPAndroidChart

Question: I try to manage text in PieChart of MPAndroidChart. But when my text is difficult situation like True = 2, False = 3 , Not = 95, in this situation my pie chart layout is very bad. Here is my code :

fun setupPieChartView() {
    mPie = findViewById(R.id.piechart)

    mPie?.setUsePercentValues(true)

    val desc: Description = Description()
    desc.text = "PieChart"
    mPie?.description = desc

    val legend: Legend? = mPie?.legend
    legend?.horizontalAlignment = Legend.LegendHorizontalAlignment.LEFT

    val value = Arrays.asList(trueAns.toFloat(), wrongAns.toFloat(), noAns.toFloat())
    val label = Arrays.asList("True", "false", "Not")

    val entry = ArrayList<PieEntry>()
    for (i in value.indices) {
        entry.add(PieEntry(value.get(i), label.get(i)))

    }


    val dataSet = PieDataSet(entry, "Result")
    dataSet.setColors(Color.GREEN, Color.RED, Color.GRAY);
    dataSet.setDrawValues(true)

    val pieData = PieData(dataSet)
    pieData.setValueFormatter(PercentFormatter())
    pieData.setValueTextSize(10f)
    pieData.setValueTextColor(Color.WHITE)

    mPie?.data = pieData
}

Result is like that :

here in my Pie-Chart data is not set in good format . Help me for this

Answer: You need this line, so your labels will be outside graph:

dataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);

And value will be outside . You can also control position, line length and coloring like this:

    pieData.setValueTextColor(Color.BLACK);
    dataSet.setValueLinePart1OffsetPercentage(10.f);
    dataSet.setValueLinePart1Length(0.43f);
    dataSet.setValueLinePart2Length(.1f);
    dataSet.setValueTextColor(Color.BLACK);
    dataSet.setXValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
    mPie.setEntryLabelColor(Color.BLUE);

Here is result:


Pie Chart Alignment issue using MPAndroidChart

Question: In my application am using piechart. But am facing an issue the alignment problem.Attaching the screenshots,Please have a look on it:

Code:

public static void chartDetails(PieChart mChart, Typeface tf) {
    mChart.animateXY(1400, 1400);
    mChart.getDescription().setEnabled(false);
    mChart.setCenterTextTypeface(tf);
    mChart.setCenterText("");
    mChart.setCenterTextSize(10f);
    mChart.setCenterTextTypeface(tf);
    // radius of the center hole in percent of maximum radius
    mChart.setHoleRadius(45f);
    mChart.setTransparentCircleRadius(50f);
    Legend l = mChart.getLegend();
    l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
    l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
    l.setOrientation(Legend.LegendOrientation.VERTICAL);
    l.setDrawInside(false);
    mChart.setTouchEnabled(true);
}

Answer: You could use outside values in order to keep clear your dataset names for small pieces of data.

For example, you could achieve something like that:

Here is the code. This code is supposed to use when overriding a PieChart. If you are not overriding it, you should adapt this code to work with your PieChart directly, such as mChart.setData(); instead of setData();.

PieDataSet dataSet = new PieDataSet(entries, null);
dataSet.setSliceSpace(3f);
dataSet.setIconsOffset(new MPPointF(0, 40));
dataSet.setSelectionShift(5f);

// Outside values
dataSet.setXValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
dataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
dataSet.setValueLinePart1OffsetPercentage(100f); /** When valuePosition is OutsideSlice, indicates offset as percentage out of the slice size */
dataSet.setValueLinePart1Length(0.6f); /** When valuePosition is OutsideSlice, indicates length of first half of the line */
dataSet.setValueLinePart2Length(0.6f); /** When valuePosition is OutsideSlice, indicates length of second half of the line */
setExtraOffsets(0.f, 5.f, 0.f, 5.f); // Ofsets of the view chart to prevent outside values being cropped /** Sets extra offsets (around the chart view) to be appended to the auto-calculated offsets.*/

PieData data = new PieData(dataSet);
data.setValueTextSize(10f);
data.setValueTextColor(Color.BLACK);
setData(data);

MPAndroidChart - all pieces of the pie chart are the same colour

Question: I am using MPAndroidChart (https://github.com/PhilJay/MPAndroidChart) library to generate pie chart. I followed multiple tutorials including the wiki page, but when I create my pie chart all of the pieces are the same color. Any idea how can I solve this ?

Code:

PieChart mChart = (PieChart) findViewById(R.id.piechart);

List<PieEntry> pieChartEntries = new ArrayList<>();

pieChartEntries.add(new PieEntry(18.5f, "Green"));
pieChartEntries.add(new PieEntry(26.7f, "Yellow"));
pieChartEntries.add(new PieEntry(24.0f, "Red"));
pieChartEntries.add(new PieEntry(30.8f, "Blue"));

PieDataSet set = new PieDataSet(pieChartEntries, "Emotion Results");
PieData data = new PieData(set);
mChart.setData(data);
set.setColors(R.color.pieColour1,R.color.pieColour2,R.color.pieColour3,R.color.pieColour4,R.color.pieColour5,R.color.pieColour6,R.color.pieColour7,R.color.pieColour8);
mChart.invalidate();

Answer: The documentation says: When adding some additional styling, the resulting PieChart with the data used above could look similar to this

These are not the real colors, but oly the labels for the colors:

pieChartEntries.add(new PieEntry(18.5f, "Green"));
pieChartEntries.add(new PieEntry(26.7f, "Yellow"));
pieChartEntries.add(new PieEntry(24.0f, "Red"));
pieChartEntries.add(new PieEntry(30.8f, "Blue"));

To add colors to the PieChart you use:

set.setColors(new int[]{Color.parseColor("#FF32DA64"),
                    Color.parseColor("#FF32DAD4"),
                    Color.parseColor("#FFB853F2"),
                    Color.parseColor("#FFF2ED53")});

or you can use one of the templates:

set.setColors(ColorTemplate.COLORFUL_COLORS);

I just saw you're using the colors from the resources, if you inspect the setColors method you should see this: If you are using colors from the resources,make sure that the colors are already prepared (by calling getResources().getColor(...))

So in your case you need to resolve the resources into Color objects before adding them to the set.


Display MPAndroidChart PieChart horizontally

Question: Is there a chart that looks like PieChart and rather than circle, numbers should be displayed in horizontal bar?

In PieChart, we display numbers in Circle. But how can i display them in single bar(horizontal)?

I need a horizontal chart for this PieChart

I tried updating my code to have horizontalbarchar and got below chart. But the values are showing wrong in the chart and also i dont want to show the other parameters which are marked in Red. Can someone help me here.

My Layout

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <com.github.mikephil.charting.charts.HorizontalBarChart
        android:id="@+id/chart1"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:background="@android:color/white" />

</RelativeLayout>

My code:

 super.onCreate(savedInstanceState);
        setContentView(R.layout.horizontal_seekbar_layout);
        mChart = findViewById(R.id.chart1);

        ArrayList<BarEntry> values=new ArrayList<>();
        values.add(new BarEntry(0,new float[]{5,3,1}));

        BarDataSet set1=new BarDataSet(values,"Summary");
        //set1.setDrawIcons(false);
        set1.setStackLabels(new String[]{"Passed","Failed","Skipped"});
        ArrayList<Integer> colors=new ArrayList<Integer>();
        colors.add(Color.GREEN);
        colors.add(Color.RED);
        colors.add(Color.GRAY);
        set1.setColors(colors);
        set1.setValueFormatter(new DecValueFormatter());

        BarData data=new BarData(set1);
        mChart.setData(data);
       // mChart.setFitBars(true);
        mChart.invalidate();

My current chart i am getting:

Answer: It can be done using stacked bar chart of mp android chart. Please follow example below to do that:

ArrayList<BarEntry> barEntries = new ArrayList<BarEntry>();
    barEntries.add(new BarEntry(0, new float[]{2,4,5,3}));


    BarDataSet barDataSet = new BarDataSet(barEntries, "Stacked Bars");
    barDataSet.setAxisDependency(YAxis.AxisDependency.LEFT);
    barDataSet.setHighlightEnabled(true);
    barDataSet.setHighLightColor(Color.RED);
    barDataSet.setColors(getColors(4,Color.RED,Color.BLUE,Color.GREEN,Color.CYAN));
    barDataSet.setStackLabels(new String[]{"Bottom","Top","Left","Right"});

    BarData barData = new BarData(barDataSet);
    barData.setValueTextSize(defaultValueTextSize);
    barData.setValueTextColor(getColor("primaryDark"));

    barChart.setDrawValueAboveBar(false); // add this line to show values inside bars
    barChart.getAxisLeft().setAxisMinimum(0);
    barChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTH_SIDED);
    barChart.animateY(1000);
    barChart.setData(barData);

This is for vertical bar just use horizontal bar chart of this library and you are good to go with buddy.


is it possible to draw a two layer Pie Chart?

Question: Hi i am trying to implement a chart like the following. Please see the image and help me find a suitable solution for this. Here i am using MPAndroidChart Library.

Right now my pie chart is look like below image.

I am using below xml

<com.github.mikephil.charting.charts.PieChart
    android:id="@+id/chart1"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

And in java, i have manage angle like that.

mChart.setMaxAngle(270f); // HALF CHART
mChart.setRotationAngle(135f);

I still have not been able to create the inner line of the pie chart. I want the graph that I already mention on top. How can I draw that line?

Answer: First you need to add MPAndroidChart library in you project. Here is the basic code I have written, you need to make changes according to your use.

MainActivity.java

public class MainActivity extends AppCompatActivity {

    PieChart mChartOuter, mChartInner;

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


        mChartOuter = (PieChart) findViewById(R.id.mChartOuter);
        mChartInner = (PieChart) findViewById(R.id.mChartInner);

        mChartOuter.getDescription().setEnabled(false);
        mChartInner.getDescription().setEnabled(false);


        mChartOuter.setCenterTextSize(10f);
        mChartInner.setCenterTextSize(10f);

        mChartOuter.setHoleRadius(75f);
        mChartInner.setHoleRadius(75f);

        mChartOuter.setTransparentCircleRadius(50f);
        mChartInner.setTransparentCircleRadius(50f);

        mChartOuter.getLegend().setEnabled(false);
        mChartInner.getLegend().setEnabled(false);

        setData();

    }

    private void setData() {

        ArrayList<PieEntry> entries = new ArrayList<PieEntry>();

        for (int i = 0; i < 5; i++) {
            entries.add(new PieEntry((float) ((Math.random() * (float) 5) + (float) 5 / 5), i));
        }

        PieDataSet dataSet = new PieDataSet(entries, "Election Results");

        dataSet.setDrawIcons(false);

        dataSet.setSliceSpace(3f);
        dataSet.setIconsOffset(new MPPointF(0, 40));
        dataSet.setSelectionShift(5f);

        ArrayList<Integer> colors = new ArrayList<Integer>();

        for (int c : ColorTemplate.VORDIPLOM_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.JOYFUL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.COLORFUL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.LIBERTY_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.PASTEL_COLORS)
            colors.add(c);

        colors.add(ColorTemplate.getHoloBlue());

        dataSet.setColors(colors);

        PieData data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter());
        data.setValueTextSize(11f);
        data.setValueTextColor(Color.WHITE);
        mChartOuter.setData(data);
        mChartInner.setData(data);

        mChartOuter.highlightValues(null);
        mChartInner.highlightValues(null);

        mChartOuter.invalidate();
        mChartInner.invalidate();
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/constraint_holder"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">


    <com.github.mikephil.charting.charts.PieChart
        android:id="@+id/mChartOuter"
        android:layout_width="600dp"
        android:layout_height="600dp"
        android:layout_centerInParent="true" />


    <com.github.mikephil.charting.charts.PieChart
        android:id="@+id/mChartInner"
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:layout_centerInParent="true" />

</RelativeLayout>

Result