The Wayback Machine - https://web.archive.org/web/20240613162442/https://www.geeksforgeeks.org/android-create-a-pie-chart-with-kotlin/
Open In App

Android – Create a Pie Chart with Kotlin

Last Updated : 31 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

A Pie Chart is a circular type of UI interface which is used to display the data in the form of percentages for different categories. This is used to display a vast amount of data. In this article, we will take a look at building a pie chart in an Android application using Kotlin.

A sample video is given below to get an idea about what we are going to do in this article.

Note: If you are looking to implement Pie Chart in Android using Java. Check out the this article: How to implement Pie Chart in Android using Java

Step-by-Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.

Note: Select Kotlin as the programming language.

Step 2: Add dependency and JitPack Repository

File Structure for navigating to gradle files is mentioned below:

gradle

-> Navigate to the Gradle Scripts > build.gradle(Module: app) and add the below dependency in the dependencies section.  

implementation("com.github.PhilJay:MPAndroidChart:v3.1.0")

-> Add the JitPack repository to your build file. Add it to your root build.gradle at the end of repositories inside the allprojects{ } section. Navigate to setting.gradle.kts file and add this snippet there.

dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()

// Add this line
maven(url = uri("https://jitpack.io"))
}
}

After adding this dependency sync your project and now we will move towards its implementation.  

Step 3: Updating colors in the Colors.xml file

File Structure for navigating to color.xml is mentioned below:

color


Add the below code to it to update the color. 

color.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="purple_200">#0F9D58</color>
    <color name="purple_500">#0F9D58</color>
    <color name="purple_700">#0F9D58</color>
    <color name="teal_200">#FF03DAC5</color>
    <color name="teal_700">#FF018786</color>
    <color name="black">#FF000000</color>
    <color name="white">#FFFFFFFF</color>
    <color name="grey">#aaa</color>
    <color name="button_color">#1E573B</color>

    <color name="yellow">#FFEB3B</color>
    <color name="red">#F44336</color>
</resources>


Step 4: Working with the activity_main.xml file

File Structure for navigating to activity_main.xml is mentioned below:

activity_main

Note: Before adding the snippet please make sure to add the icon of a circle in drawable as ic_circle.

Add the below code to that file. Below is the code for the activity_main.xml file. 

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<!--on below line we are creating a swipe to refresh layout-->
<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/idTVHead"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="4dp"
        android:gravity="center"
        android:padding="4dp"
        android:text="Pie Chart"
        android:textAlignment="center"
        android:textColor="@color/purple_200"
        android:textSize="20sp"
        android:textStyle="bold" />

    <!--Ui component for our pie chart-->
    <com.github.mikephil.charting.charts.PieChart
        android:id="@+id/pieChart"
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:layout_below="@id/idTVHead"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/pieChart"
        android:layout_marginTop="40dp"
        android:orientation="horizontal"
        android:weightSum="3">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="3dp"
            android:layout_weight="1"
            android:drawableLeft="@drawable/ic_circle"
            android:drawableTint="@color/purple_200"
            android:gravity="center"
            android:padding="4dp"
            android:text="Android"
            android:textAlignment="center"
            android:textColor="@color/black" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="3dp"
            android:layout_weight="1"
            android:drawableLeft="@drawable/ic_circle"
            android:drawableTint="@color/yellow"
            android:gravity="center"
            android:padding="4dp"
            android:text="Apple"
            android:textAlignment="center"
            android:textColor="@color/black" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="3dp"
            android:layout_weight="1"
            android:drawableLeft="@drawable/ic_circle"
            android:drawableTint="@color/red"
            android:gravity="center"
            android:padding="4dp"
            android:text="Microsoft"
            android:textAlignment="center"
            android:textColor="@color/black" />
    </LinearLayout>
  
</RelativeLayout>


Step 5: Working with the MainActivity.kt file

File Structure for navigating to MainActivity.kt is mentioned below:

MainActivity


Add the below code to it. Comments are added in the code to get to know in detail. 

MainActivity.kt
package com.gtappdevelopers.kotlingfgproject

import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.github.mikephil.charting.animation.Easing
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.formatter.PercentFormatter
import com.github.mikephil.charting.utils.MPPointF

class MainActivity : AppCompatActivity() {

    // on below line we are creating
    // variables for our pie chart
    lateinit var pieChart: PieChart

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
       
        // on below line we are initializing our 
        // variable with their ids.
        pieChart = findViewById(R.id.pieChart)

        // on below line we are setting user percent value, 
        // setting description as enabled and offset for pie chart
        pieChart.setUsePercentValues(true)
        pieChart.getDescription().setEnabled(false)
        pieChart.setExtraOffsets(5f, 10f, 5f, 5f)

        // on below line we are setting drag for our pie chart
        pieChart.setDragDecelerationFrictionCoef(0.95f)

        // on below line we are setting hole 
        // and hole color for pie chart
        pieChart.setDrawHoleEnabled(true)
        pieChart.setHoleColor(Color.WHITE)

        // on below line we are setting circle color and alpha
        pieChart.setTransparentCircleColor(Color.WHITE)
        pieChart.setTransparentCircleAlpha(110)

        // on  below line we are setting hole radius
        pieChart.setHoleRadius(58f)
        pieChart.setTransparentCircleRadius(61f)

        // on below line we are setting center text
        pieChart.setDrawCenterText(true)

        // on below line we are setting
        // rotation for our pie chart
        pieChart.setRotationAngle(0f)
        
        // enable rotation of the pieChart by touch
        pieChart.setRotationEnabled(true)
        pieChart.setHighlightPerTapEnabled(true)

        // on below line we are setting animation for our pie chart
        pieChart.animateY(1400, Easing.EaseInOutQuad)

        // on below line we are disabling our legend for pie chart
        pieChart.legend.isEnabled = false
        pieChart.setEntryLabelColor(Color.WHITE)
        pieChart.setEntryLabelTextSize(12f)

        // on below line we are creating array list and 
        // adding data to it to display in pie chart
        val entries: ArrayList<PieEntry> = ArrayList()
        entries.add(PieEntry(70f))
        entries.add(PieEntry(20f))
        entries.add(PieEntry(10f))

        // on below line we are setting pie data set
        val dataSet = PieDataSet(entries, "Mobile OS")

        // on below line we are setting icons.
        dataSet.setDrawIcons(false)

        // on below line we are setting slice for pie
        dataSet.sliceSpace = 3f
        dataSet.iconsOffset = MPPointF(0f, 40f)
        dataSet.selectionShift = 5f

        // add a lot of colors to list
        val colors: ArrayList<Int> = ArrayList()
        colors.add(resources.getColor(R.color.purple_200))
        colors.add(resources.getColor(R.color.yellow))
        colors.add(resources.getColor(R.color.red))

        // on below line we are setting colors.
        dataSet.colors = colors

        // on below line we are setting pie data set
        val data = PieData(dataSet)
        data.setValueFormatter(PercentFormatter())
        data.setValueTextSize(15f)
        data.setValueTypeface(Typeface.DEFAULT_BOLD)
        data.setValueTextColor(Color.WHITE)
        pieChart.setData(data)

        // undo all highlights
        pieChart.highlightValues(null)

        // loading chart
        pieChart.invalidate()

    }
}


Now run your application to see the output of it. 

Output:

Output of Pie Chart Kotlin


Note : To access the full android application using Pie chat check this repository: Pie Chart Android Application


Click Here to Learn More about Android Development in Kotlin



Similar Reads

Pie Chart in Android using Jetpack Compose
Pie Chart is seen used in many android applications for displaying a huge quantity of data in a simple and easy format. This is seen in applications where a huge quantity of data is to be handled. In this article, we will take a look at How to Create Pie Chart in Android using Jetpack Compose. A sample video is given below to get an idea about what
8 min read
How to add a Pie Chart into an Android Application
A Pie Chart is a circular statistical graphic, which is divided into slices to illustrate numerical proportions. It depicts a special chart that uses “pie slices”, where each sector shows the relative sizes of data. A circular chart cuts in the form of radii into segments describing relative frequencies or magnitude also known as a circle graph. A
7 min read
Android - Create a Scatter Chart to Represent Data using Kotlin
Many applications prefer displaying a huge amount of data in the form of charts. There are different types of charts used in the application to display this huge amount of data such as pie charts, bar graphs, and scattered charts. In this article, we will look at How to Create a Scatter Chart in Android to represent data using Kotlin. Note: If you
6 min read
Creating a Anagram Checker Android App in Android Studio with Kotlin
An anagram of a word is another word that contains the same characters, only the order of characters can be different. For example, “abcd” and “dabc” are an anagram of each other. In this article, we will be building an Anagram Checker android app in Android Studio using Kotlin and XML. The app will check whether the entered words are anagrams of e
3 min read
Android - Create Group BarChart with Kotlin
Bar Charts in android are used to represent vast amounts of data in an easily readable format. We can display a single bar chart within our bar chart. But for making a comparison between two categories we can implement a group bar chart to display data for both categories side by side. In this article, we will be building a simple Group Bar Chart i
5 min read
Create an Android App that Displays List of All Trending Kotlin git-hub Repositories
Kotlin is a popular programming language that has gained much attention in recent years. It is known for its simplicity, conciseness, and compatibility with existing Java code. GitHub is a popular platform for hosting and sharing code, including Kotlin projects. This article will discuss how to build an application that shows a list of Kotlin GitHu
12 min read
How to Create a Dark Mode for a Custom Android App in Kotlin?
The dark mode is a feature that allows you to switch the color theme of an app or a whole OS to black or something on the brink of it. Beyond the joys of invigorating a tired design, one may wish to choose because it makes watching the device screen way more comfortable and relaxing on the eyes. Typical pixel values during the regular mode fall bet
3 min read
How to Create a Splash Screen in Android using Kotlin?
Android Splash Screen is the first screen visible to the user when the application’s launched. Splash Screen is the user's first experience with the application that's why it is considered to be one of the most vital screens in the application. It is used to display some information about the company logo, company name, etc. We can also add some an
3 min read
How to Create Your Own Custom View in Android with Kotlin?
In this article, we're going to talk about how we can create our own custom view in Android step by step. We all know that in the beginning android platform provides us some basic views for example - TextView, ImageView, EditText, Button, ImageButton, RadioButton, etc. But, sometimes we need a whole new type of view where our prebuilt layouts and w
4 min read
How to Create Option Menu in Android using Kotlin?
In this article, we will learn how to create an options menu in the Android app using Kotlin. To have an options menu in an Activity, we need to create a new menu XML file and inflate it using menuInflator.inflate( ) method. In menu.xml we will design the options menu as the requirement of the app. Step by Step Implementation Step 1: Create a New P
2 min read