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

 

22 comments:

  1. I have an app for learning Android:
    https://play.google.com/store/apps/details?id=arjuntoshniwal.androidtutorials.advanced&hl=en

    ReplyDelete
  2. I would like to thank you for the efforts you have made in writing this article, Its good and Informative.
    android online training

    ReplyDelete
  3. It’s very informative and you are obviously very knowledgeable in this area. You have opened my eyes to varying views on this topic with interesting and solid content. Tubidy Mobile Music MP3 Downloader Download

    ReplyDelete
  4. Nice information, valuable and excellent in Job, as share good stuff with good ideas and concepts, lots of great information and inspiration, both of which I need, thanks to offer such a helpful information here.
    mobile phone repair in Canton
    iphone repair in Canton
    cell phone repair in Canton
    tablet repair in Canton
    ipad repair in Canton
    phone repair in Canton
    mobile phone repair canton
    iphone repair canton
    cell phone repair canton
    phone repair canton

    ReplyDelete
  5. I need to communicate my deference of your composing aptitude and capacity to make perusers read from the earliest starting point as far as possible. I might want to peruse more up to date presents and on share my musings with you.https://360digitmg.com/course/certification-program-in-data-science

    ReplyDelete
  6. Nice stuff!! It's good to share these types of articles and I hope you'll share an article about artificial intelligence. By giving an institute like 360DigiTMG.it is one of the best institutes for accredited courses.
    artificial intelligence course in delhi

    ReplyDelete
  7. "
    Viably, the article is actually the best point on this library related issue. I fit in with your choices and will enthusiastically foresee your next updates.
    "
    HRDF training

    ReplyDelete
  8. "I was just examining through the web looking for certain information and ran over your blog.It shows how well you understand this subject. Bookmarked this page, will return for extra." https://360digitmg.com/course/artificial-intelligence-ai-and-deep-learning

    ReplyDelete
  9. I truly like your style of blogging. I added it to my preferred's blog webpage list and will return soon…
    360DigiTMG iot

    ReplyDelete
  10. Here is the site(bcomexamresult.in) where you get all Bcom Exam Results. This site helps to clear your all query.
    BA 3rd year Result 2020
    RTMNU BCOM 3rd Year Result 2020

    ReplyDelete
  11. I think you did an awesome rbse 12th result job explaining it. Sure beats having to research BA 3rd year Exam result it on my own. Thanks

    ReplyDelete
  12. https://bklaw.attorney/Top-Factors-Influencing-Bankruptcy-in-Fairfax-Virginia.html

    ReplyDelete
  13. It is more than just scanning resumes and profiles when hiring solidity developers. If you have no experience in hiring Solidity Developers, these resources can provide you with some input and make the process easier.

    ReplyDelete
  14. Thank you for every other informative web site. Where else may I am getting that kind of information written in such a perfect way? I’ve a undertaking that I’m just now working on, and I have been on the look out for such information.

    BCA Time Table - B.C.A I II III Ka Exam Routine 2022
    Cusat University Time Table 2022
    Datta Meghe University Time Table 2022
    JRRSU Exam Time Table 2022

    ReplyDelete
  15. We offer high-quality and cost-effective services for web & mobile app development.react js agency

    ReplyDelete
  16. Develop modern & human-centric apps for increased retention and conversion with CronJ's react development services.

    ReplyDelete
  17. It's Nice!
    Thanks for sharing such an amazing blog! If you are looking to hire dedicated Android app Developers then connect with us to hire top talent!

    ReplyDelete