Android Pie Chart using MpAndroid Library Tutorial

19

This tutorial explains how to implement Pie Chart in a simple Android Application example.



piechart_studytutorial

Introduction

A Pie Chart or Pie Graph is a type of graph in which a circle is divided into sectors that each represent a proportion of the whole.

Create a new project

To implement Pie chart, we are going to create a new android project. Go to File ⇒ New ⇒ New Projects in Android studio.

Add MpAndroid library

We need to add MpAndroid library in our project, so open build.gradle(Module:app) file and add following code:

repositories {
    maven { url "https://jitpack.io" }
}

dependencies {
   .....
    compile 'com.github.PhilJay:MPAndroidChart:v2.2.4'
   .....
}

Create Layout

We will use com.github.mikephil.charting.charts xml tag in layout to create Pie Chart

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

Initialize PieChart

We need to initialize id of Pie Chart.

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

Enable DataSet in Percentage

If we want to add Y-values in percentage then we need to call setUsePercentValues(true).

 pieChart.setUsePercentValues(true);

Creating Dataset

Every individual value of the raw data should be represented as an Entry. An ArrayList of such Entry objects is used to create a DataSet.

 // 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<Entry> yvalues = new ArrayList<Entry>();
        yvalues.add(new Entry(8f, 0));
        yvalues.add(new Entry(15f, 1));
        yvalues.add(new Entry(12f, 2));
        yvalues.add(new Entry(25f, 3));
        yvalues.add(new Entry(23f, 4));
        yvalues.add(new Entry(17f, 5));

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

Defining X-axis labels Or X-values

Without using labels, there is no meaningful sense of already added value to the chart. We can use an ArrayList is to store x-axis labels. Pass the X-values Array and dataset into a new object PieData.

 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(xVals, dataSet);

Set Value Formatter

If you want to display chart in percentage then pass new PercentFormatter() as a parameter otherwise pass new DefaultValueFormatter(0). new DefaultValueFormatter(0) parameter show data value.

// In percentage Term
data.setValueFormatter(new PercentFormatter());
// Default value
//data.setValueFormatter(new DefaultValueFormatter(0));

  • piechart_studytutorial
  • Android Pie Chart


Set Data

To create Pie Chart with data, we need to pass the pie data into setData() method. If we do not pass the PieData into a setData() Method then create an empty Pie Chart.

pieChart.setData(data);

Run App

Now run app, we will see Simple Pie Chart with data.

pie_chart_studytutorial

Set the colors

We can change the default color by using setColors() method. MpAndroidChart library also provides predefined color templates.

dataSet.setColors(ColorTemplate.VORDIPLOM_COLORS);
OR
dataSet.setColors(ColorTemplate.JOYFUL_COLORS);
OR
dataSet.setColors(ColorTemplate.COLORFUL_COLORS);
OR
dataSet.setColors(ColorTemplate.LIBERTY_COLORS);
OR
dataSet.setColors(ColorTemplate.PASTEL_COLORS);

colorful_pie_chart_studytutorial

Set the Description

We can add the description to the chart by using setDescription(“Your description”) Method

pieChart.setDescription("This is Pie Chart");

Enable and Disable Hole

By default, MpAndroid library create a Pie Chart with hole. We will control Hole in the pie chart by using setDrawHoleEnabled() method. If we pass false as argument in this method the it will disable hole in the Pie Chart and If we want to enable hole then pass in it true as argument.

//Disable Hole in the Pie Chart
pieChart.setDrawHoleEnabled(false);

disable_hole_piechart

Enable Hole

To enable hole in the Pie chart then Pass the true argument in the setDrawHoleEnabled() method. We can control radius of hole by using setHoleRadius().

pieChart.setDrawHoleEnabled(true);
pieChart.setTransparentCircleRadius(30f);
pieChart.setHoleRadius(30f);

pie_chart_with_hole

Set the Text Size and Text Color

We can define text size and also color for the Pie Chart

data.setValueTextSize(13f);
data.setValueTextColor(Color.DKGRAY);

pie_chart_tutorial

Implements OnChartValueSelectedListener

To get the value on the touch or select, we need to implement onChartValueSelectedListner and add onValueSelected() method to get response.


public class MainActivity extends AppCompatActivity implements OnChartValueSelectedListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        PieChart pieChart = (PieChart) findViewById(R.id.piechart);
        pieChart.setUsePercentValues(true);

        // 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<Entry> yvalues = new ArrayList<Entry>();
        yvalues.add(new Entry(8f, 0));
        yvalues.add(new Entry(15f, 1));
        yvalues.add(new Entry(12f, 2));
        yvalues.add(new Entry(25f, 3));
        yvalues.add(new Entry(23f, 4));
        yvalues.add(new Entry(17f, 5));

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

        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(xVals, dataSet);
        // In Percentage
        data.setValueFormatter(new PercentFormatter());
        // Default value
        //data.setValueFormatter(new DefaultValueFormatter(0));
        pieChart.setData(data);
        pieChart.setDescription("This is Pie Chart");
        pieChart.setDrawHoleEnabled(true);
        pieChart.setTransparentCircleRadius(58f);

        pieChart.setHoleRadius(58f);
        dataSet.setColors(ColorTemplate.VORDIPLOM_COLORS);

        data.setValueTextSize(13f);
        data.setValueTextColor(Color.DKGRAY);

        pieChart.setOnChartValueSelectedListener(this);


    }

    @Override
    public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {

        if (e == null)
            return;
        Log.i("VAL SELECTED",
                "Value: " + e.getVal() + ", xIndex: " + e.getXIndex()
                        + ", DataSet index: " + dataSetIndex);
    }

    @Override
    public void onNothingSelected() {
        Log.i("PieChart", "nothing selected");
    }

}

Adding Animations

This library support animations, which you can use to make your charts appear more lively. The animateXY method is used to animate both axes of the chart. If you want to animate only one of the axes, you can use animateX oranimateY to animate the x-axis or y-axis respectively. You have to specify the duration (in milliseconds) of the animation when you call these methods. For example, to only animate the y-Axis, add the following code snippet:

pieChart.animateXY(1400, 1400);

Final Code

package in.studytutorial.androidpiechart;

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.SeekBar;

import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements OnChartValueSelectedListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        PieChart pieChart = (PieChart) findViewById(R.id.piechart);
        pieChart.setUsePercentValues(true);

        // 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<Entry> yvalues = new ArrayList<Entry>();
        yvalues.add(new Entry(8f, 0));
        yvalues.add(new Entry(15f, 1));
        yvalues.add(new Entry(12f, 2));
        yvalues.add(new Entry(25f, 3));
        yvalues.add(new Entry(23f, 4));
        yvalues.add(new Entry(17f, 5));

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

        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(xVals, dataSet);
        // In Percentage term
        data.setValueFormatter(new PercentFormatter());
        // Default value
        //data.setValueFormatter(new DefaultValueFormatter(0));
        pieChart.setData(data);
        pieChart.setDescription("This is Pie Chart");

        pieChart.setDrawHoleEnabled(true);
        pieChart.setTransparentCircleRadius(25f);
        pieChart.setHoleRadius(25f);

        dataSet.setColors(ColorTemplate.VORDIPLOM_COLORS);
        data.setValueTextSize(13f);
        data.setValueTextColor(Color.DKGRAY);
        pieChart.setOnChartValueSelectedListener(this);

        pieChart.animateXY(1400, 1400);

    }

    @Override
    public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {

        if (e == null)
            return;
        Log.i("VAL SELECTED",
                "Value: " + e.getVal() + ", xIndex: " + e.getXIndex()
                        + ", DataSet index: " + dataSetIndex);
    }

    @Override
    public void onNothingSelected() {
        Log.i("PieChart", "nothing selected");
    }

}



 


  • hi thanks for share #bookmark

    • abhayanand1910

      Welcome

  • Rajalakshmi Vasikaran

    how to create piechart dynamically after fetching data from server

    • See my httpurlconnection tutorial to get server data as json. When are you creating Arraylist put it into dynamic values.

      • Rajalakshmi Vasikaran

        Thank you for your quick reply. I am new to android.
        My requirement is…
        I need to fetch data from server using Php and pass data as json and display as piechart (mobile side) Already I tried static piechart(without getting data from server), it works fine. I don’t know how to do dynamically.plz help me

    • I have already posted, how to get data from server. Search httpurlconnection in search box. Use this tutorial to get data as response.

      • Rajalakshmi Vasikaran

        Thank you.
        I have completed server code. I got json output. I don’t knw..how to pass that json value to create piechart dynamically

        • try {
          JSONObject json = new JSONObject(response);
          final String serverResponse = json.getString(“Your Index”);

          } catch (Exception e){
          e.printStackTrace();
          }

          • Nitin Bhargava

            I’m using asynctask to fetch the json output from the webservice. I’m able to get the yvalues for the pie chart as Float variables. How do I set the yvalues in onPostExecute() method?

          • in PostExecute(), you need to execute code with in run() method.

            MainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
            }
            });

    • Where you got response, Use youe code with in run Method

      MainActivity.this.runOnUiThread(new Runnable() {
      @Override
      public void run() {
      }
      });

  • harsha

    how to display exact values instead of percentage

    • Use data.setValueFormatter(new DefaultValueFormatter(0));

  • Venkata Ravi Kumar Kuruva

    How to set Pie chart in Fragment. I taken navigable drawer which is consists of 5 fragments as a Menu I made first fragment as home page in that page I want to create pie chart using json data please help me

  • Williams Levy

    how to avoid overlapping piechart data when data is getting from webservices

  • Jay Halani

    Please add an article about how to use MPAndroid with Realm Database.