Tuesday 5 November 2019

Android Pie Chart using MPAndroidChart library

This tutorial is to help you learn pie chart view by developing an Android pie chart example app using MPAndroidChart library. It is a free Android chart view / graph view library using which you can draw line, bar, pie, radar, bubble, candlestick,scatter charts.
There are times when we deal with large datasets. In those scenarios, it is quite useful to use charts and graphs to get visual representation of data. In Android there are various other opensource libraries available to build the same chart. So we just picked a popular library,  MPAndroidChart. Also we have taken the sample data to show case in this pie chart, which  displaying my besties name & their corresponding age's. 



Lets begin :)

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 file and add following code:

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

 dependencies {

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

 

Add the following code in res/layout file.(layout_piechart.xml) 

 <?xml version="1.0" encoding="utf-8"?>
<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.PieChart
android:id="@+id/rkt_pie_chart"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
</RelativeLayout>


Rkt_ChartActivity.java

 



package mobiappdeveloper;

import android.graphics.Color;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.github.mikephil.charting.utils.MPPointF;

import java.text.DecimalFormat;
import java.util.ArrayList;

import www.mobiappdeveloper.com.R;




public class Rkt_ChartActivity extends AppCompatActivity {

private PieChart chart;


String setLabel[] = {"Baba(Age)", "Mallu(Age)", "Sikari(Age)", "Rkt(Age)", "Chuha(Age)"};

float getRandomValue[] = {70f, 40f, 60f, 30f, 0f};

final int[] MY_COLORS = {Color.rgb(192,0,0), Color.rgb(255,0,0), Color.rgb(255,192,0),
Color.rgb(127,127,127), Color.rgb(146,208,80), Color.rgb(0,176,80), Color.rgb(79,129,189)};
ArrayList<Integer> colors = new ArrayList<>();



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


chart = findViewById(R.id.rkt_pie_chart);
chart.setUsePercentValues(false);
chart.getDescription().setEnabled(false);
chart.setExtraOffsets(5, 10, 5, 10);
chart.setDragDecelerationFrictionCoef(0.92f);
chart.setCenterText("");

chart.setDrawHoleEnabled(false);
chart.setHoleColor(Color.WHITE);

chart.setTransparentCircleColor(Color.WHITE);
chart.setTransparentCircleAlpha(110);

chart.setHoleRadius(58f);
chart.setTransparentCircleRadius(61f);

chart.setDrawCenterText(true);

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

chart.getLegend().setEnabled(false);


chart.setEntryLabelColor(Color.WHITE);

chart.setEntryLabelTextSize(11f);



/* chart.setDrawMarkers(false); // To remove markers when click
chart.setDrawEntryLabels(false); // To remove labels from piece of pie
chart.getDescription().setEnabled(false); // To remove description of pie*/


setData();

//Rkt pls comment below value if u dont need any Animate in pie chart
chart.animateXY(1400, 1400);


}


private void setData() {
ArrayList<PieEntry> entries = new ArrayList<>();

for (int i = 0; i < 5; i++) {
if (getRandomValue[i] > 0) {
entries.add(new PieEntry(getRandomValue[i], setLabel[i]));
/* colors.add(pickColors[i]);*/
}

}

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

dataSet.setDrawIcons(false);

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



for(int c: MY_COLORS) colors.add(c);

dataSet.setColors(colors);


PieData data = new PieData(dataSet);
data.setValueFormatter(new MyDecimalFormator(new DecimalFormat("###,###,###")));
data.setValueTextSize(11f);
data.setValueTextColor(Color.WHITE);


chart.setData(data);


chart.highlightValues(null);

chart.invalidate();
}


}





MyDecimalFormator.java




package mobiappdeveloper;

import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.utils.ViewPortHandler;

import java.text.DecimalFormat;

public class MyDecimalFormator extends PercentFormatter {


protected DecimalFormat mFormat;

public MyDecimalFormator(DecimalFormat format) {
this.mFormat = format;
}

@Override
public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
return mFormat.format(value) + " ";
}
}





Some bonus points : 


1) Animate XY of the chart
chart.animateXY(1400, 1400);

2) Show details about chart.
chart.getLegend().setEnabled(true);

3) Use holo circle at center of pie chart
chart.setDrawHoleEnabled(true); 


4) Dont want to show the label/pie etc for 0 value or for other condition, just edit below condition

if (getRandomValue[i] > 0) {
entries.add(new PieEntry(getRandomValue[i], setLabel[i]));
}


5) Give your own color to each pie
for(int c: MY_COLORS) colors.add(c);


6) Wana your own format within value
return mFormat.format(value) + " ";

Concatenate any value like $,% etc in above line in MyDecimalFormator.java





Now lets run and test the application.

Example Application Output :

 

 

Download the Source Code : 

http://www.mobiappdeveloper.com