Open In App

How to Create a BarChart in Android?

Last Updated : 13 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

If you are looking for a UI component to represent a huge form of data in easily readable formats then you can think of displaying this huge data in the form of bar charts or bar graphs. It makes it easy to analyze and read the data with the help of bar graphs. In this article, we will take a look at the implementation of bar graphs in Android. 

CreateaBarChartinAndroid-ezgifcom

What are we going to build in this article? 

We will be building a simple application in which we will be displaying a bar chart with some sample data in it. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java/Kotlin language. 

Important Attributes of BarChart

Attributes

Description

setDatato set bar data in our bar chart.
setColorsto set colors to our bar chart.
setValueTextColorto set the color for our text in the bar graph.
setValueTextSizeto set text size for our value
getDescriptionto get the description of our bar chart. 


Step-by-Step Implementation

Step 1: Create a New Project

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

Note that select Java/Kotlin as the programming language.


Step 2: Add dependency and JitPack Repository

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.

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

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


Step 3: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.

activity_main.xml: 

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Bar Chart Graph"
        android:textSize="30sp"
        android:layout_marginTop="40sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <!--Ui component for our bar chart-->
    <com.github.mikephil.charting.charts.BarChart
        android:id="@+id/idBarChart"
        android:layout_width="350sp"
        android:layout_height="700sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

</androidx.constraintlayout.widget.ConstraintLayout>

Demo UI:

BarChart


Step 4: Working with the MainActivity.java file

Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.

MainActivity File:

Java
package com.gfg.barchart_java;

import android.graphics.Color;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    BarChart barChart;
    BarDataSet barDataSet;
    ArrayList<BarEntry> barEntries;

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

        // Working on DataSet
        barDataSet = new BarDataSet(getBarEntries(), "Data");
        
        // Option 2: Set different colors for each bar
        int[] colors = {Color.RED, Color.GREEN, Color.BLUE,
                Color.YELLOW, Color.CYAN, Color.MAGENTA};

        // Set the colors for the bars
        barDataSet.setColors(colors); 

        barDataSet.setValueTextSize(11f);

        // Working on BarChart
        barChart = findViewById(R.id.idBarChart);
        BarData data = new BarData(barDataSet);
        barChart.setData(data);
        barChart.animateY(2000);
        barChart.getDescription().setEnabled(false);
        barChart.setDragEnabled(true);
        barChart.setVisibleXRangeMaximum(6);

        // Set bar width
        data.setBarWidth(0.15f);

        // X-Axis Data
        XAxis xAxis = barChart.getXAxis();
        xAxis.setCenterAxisLabels(true);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setGranularity(1);
        xAxis.setGranularityEnabled(true);

        // Enable grid lines for X-axis
        xAxis.setDrawGridLines(true);

        // Set grid line color
        xAxis.setGridColor(Color.LTGRAY);

        // Set grid line width
        xAxis.setGridLineWidth(1f); 

        // Y-Axis Data
        YAxis leftAxis = barChart.getAxisLeft();
        leftAxis.setDrawGridLines(true); 
        leftAxis.setGridColor(Color.LTGRAY); 
        leftAxis.setGridLineWidth(1f); 
        leftAxis.setTextColor(Color.WHITE); 

        YAxis rightAxis = barChart.getAxisRight();

        // Disable right Y-axis
        rightAxis.setEnabled(false); 

        barChart.getXAxis().setAxisMinimum(0);
        barChart.animate();

        // Invalidate the chart to refresh
        barChart.invalidate();
    }

    // ArrayList for the first set of bar entries
    private ArrayList<BarEntry> getBarEntries() {
        // Creating a new ArrayList
        barEntries = new ArrayList<>();

        // Adding entries to the ArrayList for the first set
        barEntries.add(new BarEntry(1f, 3));
        barEntries.add(new BarEntry(2f, 5));
        barEntries.add(new BarEntry(3f, 7));
        barEntries.add(new BarEntry(4f, 1));
        barEntries.add(new BarEntry(5f, 2));
        barEntries.add(new BarEntry(6f, 6));

        return barEntries;
    }
}
Kotlin
package com.gfg.bar_kotlin

import android.graphics.Color
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.github.mikephil.charting.charts.BarChart
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.components.YAxis
import com.github.mikephil.charting.data.BarData
import com.github.mikephil.charting.data.BarDataSet
import com.github.mikephil.charting.data.BarEntry

class MainActivity : AppCompatActivity() {

    private lateinit var barChart: BarChart
    private lateinit var barDataSet: BarDataSet
    private lateinit var barEntries: ArrayList<BarEntry>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Working on DataSet
        barDataSet = BarDataSet(barEntriesList, "Data")

        // Option 2: Set different colors for each bar
        val colors = intArrayOf(
            Color.RED, Color.GREEN, Color.BLUE,
            Color.YELLOW, Color.CYAN, Color.MAGENTA
        )

        // Set the colors for the bars
        barDataSet.colors = colors.toList()

        barDataSet.valueTextSize = 11f

        // Working on BarChart
        barChart = findViewById(R.id.idBarChart)
        val data = BarData(barDataSet)
        barChart.data = data
        barChart.animateY(2000)
        barChart.description.isEnabled = false
        barChart.isDragEnabled = true
        barChart.setVisibleXRangeMaximum(6f)

        // Set bar width
        data.barWidth = 0.15f

        // X-Axis Data
        val xAxis: XAxis = barChart.xAxis
        xAxis.position = XAxis.XAxisPosition.BOTTOM
        xAxis.granularity = 1f
        xAxis.isGranularityEnabled = true

        // Enable grid lines for X-axis
        xAxis.setDrawGridLines(true)

        // Set grid line color
        xAxis.gridColor = Color.LTGRAY

        // Set grid line width
        xAxis.gridLineWidth = 1f

        // Y-Axis Data
        val leftAxis: YAxis = barChart.axisLeft
        leftAxis.setDrawGridLines(true)
        leftAxis.gridColor = Color.LTGRAY
        leftAxis.gridLineWidth = 1f
        leftAxis.textColor = Color.WHITE

        val rightAxis: YAxis = barChart.axisRight

        // Disable right Y-axis
        rightAxis.isEnabled = false

        barChart.xAxis.axisMinimum = 0f
        barChart.animate()

        // Invalidate the chart to refresh
        barChart.invalidate()
    }

    // ArrayList for the first set of bar entries
    private val barEntriesList: ArrayList<BarEntry>
        get() {
            // Creating a new ArrayList
            barEntries = ArrayList()

            // Adding entries to the ArrayList for the first set
            barEntries.add(BarEntry(1f, 3f))
            barEntries.add(BarEntry(2f, 5f))
            barEntries.add(BarEntry(3f, 7f))
            barEntries.add(BarEntry(4f, 1f))
            barEntries.add(BarEntry(5f, 2f))
            barEntries.add(BarEntry(6f, 6f))

            return barEntries
        }
}


Now run your app and see the output of the app. 

Output:



Next Article

Similar Reads