Android Pie Chart using MpAndroid Library Tutorial

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 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.

data.setValueFormatter(new PercentFormatter());
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);
        data.setValueFormatter(new PercentFormatter());
        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);
        data.setValueFormatter(new PercentFormatter());
        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");
    }

}

 


The following two tabs change content below.
Abhay Anand has experience in the field of Software Development. He can program Android, PHP, JavaScript, Html, Css. He develops web and Android applications. You can reach him at anand.abhay1910@gmail.com
  • hi thanks for share #bookmark