Skip to main content

Android Bar Chart Using MpAndroidChart Library Tutorial



Android Bar Chart Using MpAndroidChart Library Tutorial


Objective











In this tutorial we learn how to implement Bar Chart using MpAndroidChart Library in your Android App.















  

https://www.numetriclabz.com/wp-content/uploads/2015/12/9.jpg

  
Step 1

Contents
·       1 Introduction
·       2 Creating Bar chart

Introduction

A Chart, also called Graph, is a graphical representation of data in which data is represented by symbols such as bars, lines, bubbles etc.
Using MpAndroidChart Library, we can draw various graph but focus of this tutorial will be on Bar chart. A Bar Chart is a diagram in which the numerical values of variables are represented by the height or length of lines or rectangles of equal width. This Library works for Android API 8 and above but if we are using animations, it needs API 11 and above.

Step 2

Creating Bar chart

Step 2.1

Create a new Project

Create a new Project in android Studio goto File New New Projects.

 
Step 2.2

Adding library in Project

To draw Bar Chart, we need to compile MpAndroidChart Library in our project. Open your build.gradle file and use the following code to compile MpAndroidChart Library.
Open build.gradle file and use the following code to compile 
MpAndroidChart Library.
1
2
3
4
5
6
7
<br />
repositories {<br />
    maven { url &quot;Error! Hyperlink reference not valid. }<br />
}</p>
<p>dependencies {<br />
    compile 'com.github.PhilJay:MPAndroidChart:v2.1.6'<br />
}<br />

Step 2.3

Create Layout


To create a Bar chart in Android, we need to use
com.github.mikephil.charting.charts.BarChart xml tag in layout xml file. If we want to create Bar chart horizontally then we need to usecom.github.mikephil.charting.charts.HorizontalBarChart xml tag in layout xml file.This tag creates the view of Bar chart. Use the following code in activity layout

Vertical Bar chart
1
2
3
4
5
6
<br />
 &lt;com.github.mikephil.charting.charts.BarChart<br />
            android:id=&quot;@+id/chart&quot;<br />
            android:layout_width=&quot;match_parent&quot;<br />
            android:layout_height=&quot;match_parent&quot; /&gt;</p>
<p>

If we want to make horizontal bar chart, use this code in your layout
1
2
3
4
5
<br />
&lt;com.github.mikephil.charting.charts.HorizontalBarChart<br />
            android:id=&quot;@+id/chart&quot;<br />
            android:layout_width=&quot;match_parent&quot;<br />
            android:layout_height=&quot;300dp&quot; /&gt;<br />

Step 2.4

To Plot Bar Chart


Step 2.4.1

Initialize the graph id

Initialize the graph id to use the feature of graph
for vertical Bar chart
1
2
3
<br />
// To make vertical bar chart, initialize graph id this way<br />
 BarChart barChart = (BarChart) findViewById(R.id.chart);<br />

for horizontal Bar chart
1
2
3
<br />
// to make horizontal bar chart, initialize graph id this way<br />
 HorizontalBarChart barChart = (HorizontalBarChart) findViewById(R.id.chart);<br />
Step 2.4.2

Creating a Dataset

All data should be converted into a DataSet object before it can be used by a chart. Different types of charts use different subclasses of the DataSet class.
To display the data in a Bar chart, we need to create a BarDataSet instance. BarDataSet is the Subclass of DataSet class.

Every individual value of the raw data should be represented as an BarEntry. An ArrayList of such BarEntry objects is used to create a DataSet.

1
2
3
4
5
6
7
8
<br />
        ArrayList&lt;BarEntry&gt; entries = new ArrayList&lt;&gt;();<br />
        entries.add(new BarEntry(4f, 0));<br />
        entries.add(new BarEntry(8f, 1));<br />
        entries.add(new BarEntry(6f, 2));<br />
        entries.add(new BarEntry(12f, 3));<br />
        entries.add(new BarEntry(18f, 4));<br />
        entries.add(new BarEntry(9f, 5));<br />

Now, initialize the BarDataSet and pass the argument as an ArrayList of BarEntry object.
1
2
<br />
BarDataSet dataset = new BarDataSet(entries, &quot;# of Calls&quot;);<br />

Step 2.4.3

Defining X-axis labels

Without using labels, there is no meaningful sense of already added value to the chart. We can use an ArrayList to store x-axis label.

1
2
3
4
5
6
7
8
9
10
<br />
// creating labels<br />
  ArrayList&lt;String&gt; labels = new ArrayList&lt;String&gt;();<br />
        labels.add(&quot;January&quot;);<br />
        labels.add(&quot;February&quot;);<br />
        labels.add(&quot;March&quot;);<br />
        labels.add(&quot;April&quot;);<br />
        labels.add(&quot;May&quot;);<br />
        labels.add(&quot;June&quot;);</p>
<p>

Step 2.4.4

Set the data

Now, we need to initialize the BarData class with argument as a list of labels and dataset and set the Bar data into Bar chart. If we do not set the BarData into Bar chart, we will create an empty Bar chart.

1
2
3
<br />
BarData data = new BarData(labels, dataset);<br />
barChart.setData(data); // set the data and list of lables into chart<br />

Step 2.4.5

Add the description to the chart

We can add the description to the chart via .setDescription(“Your description”);

1
2
<br />
barChart.setDescription(&quot;Description&quot;);  // set the description<br />

Step 2.4.6

Run your App

Now, Run app on a android device and you will see a Scatter chart . This chart is interactive and responds to pinch-to-zoom and dragging gestures.


Vertical bar chart
9

 
Horizontal bar chart
1

 
Step 2.4.7

Set the color

If you do not like default color, you can use the Dataset class setcolor method change the color scheme. However, MPAndroidChart also comes with a number of predefined color templates that let you change the look and feel of your data set without having to deal with the individual color values.
1
2
<br />
dataset.setColors(ColorTemplate.COLORFUL_COLORS);<br />
Vertical bar chart
https://www.numetriclabz.com/wp-content/uploads/2015/12/6.jpg

 
Horizontal bar chart

0

 
Step 2.4.8

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:
1
2
<br />
 barChart.animateY(5000);<br />

Step 2.5

To plot grouped bar chart

Now I am going to explain bar chart which has two group.
 
Step 2.5.1

Creating Dataset

Every individual value of the raw data should be represented as an BarEntry. An ArrayList of such BarEntry objects is used to create a own DataSet.

Now, we are going to create two individual DataSet and these dataset combined into an ArrayList. Type of this ArrayList is BarDataSet. Now, we will initialize the BarData class with argument list of labels and list of DataSet. Set the BarData into chart via .setData();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<br />
        // create BarEntry for group 1<br />
        ArrayList&lt;BarEntry&gt; group1 = new ArrayList&lt;&gt;();<br />
        group1.add(new BarEntry(4f, 0));<br />
        group1.add(new BarEntry(8f, 1));<br />
        group1.add(new BarEntry(6f, 2));<br />
        group1.add(new BarEntry(12f, 3));<br />
        group1.add(new BarEntry(18f, 4));<br />
        group1.add(new BarEntry(9f, 5));</p>
<p>        // create BarEntry for group 1<br />
        ArrayList&lt;BarEntry&gt; group2 = new ArrayList&lt;&gt;();<br />
        group2.add(new BarEntry(6f, 0));<br />
        group2.add(new BarEntry(7f, 1));<br />
        group2.add(new BarEntry(8f, 2));<br />
        group2.add(new BarEntry(12f, 3));<br />
        group2.add(new BarEntry(15f, 4));<br />
        group2.add(new BarEntry(10f, 5));</p>
<p>        BarDataSet barDataSet1 = new BarDataSet(group1, &quot;Brand 1&quot;);  // creating dataset for group1<br />
        //barDataSet1.setColor(Color.rgb(0, 155, 0));<br />
        barDataSet1.setColors(ColorTemplate.COLORFUL_COLORS);</p>
<p>        BarDataSet barDataSet2 = new BarDataSet(group2, &quot;Brand 2&quot;); // creating dataset for group1<br />
        barDataSet2.setColors(ColorTemplate.COLORFUL_COLORS);</p>
<p>        ArrayList&lt;BarDataSet&gt; dataSets = new ArrayList&lt;&gt;();  // combined all dataset into an arraylist<br />
        dataSets.add(barDataSet1);<br />
        dataSets.add(barDataSet2);</p>
<p>        BarData data = new BarData(labels, dataSets); // initialize the Bardata with argument labels and dataSet<br />
        barChart.setData(data);</p>
<p>
https://www.numetriclabz.com/wp-content/uploads/2015/12/9.jpg

  



  
If there is any issue or need any kind of help with the numAndroidCharts library then please raise an issue at GitHub. We will try to provide a solution for that as soon as possible. 
https://github.com/numetriclabz/numAndroidCharts



Q2>



Android Chart Example APP using MPAndroidChart



This tutorial is to help you learn chart view by developing an Android chart example APP using the library MPAndroidChart. It is a free Android chart view / graph view library using which you can draw line, bar, pie, radar, bubble, candlestick 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 world, charts can be easily built using various libraries.
ndroid Chart Example
MPAndroidChart also supports scaling, dragging and animations. It is a popular library available via GitHub. Earlier I have published another tutorial for creating Android APPs with chart using AndroidPlot, you can refer that for alternate library.
In this Android chart example tutorial, I will demonstrate how to use MPAndroidChart library by building a demo Android App. We’ll create an example Android chart application which will display year wise strength of employees in an organization. Also, we will build a bar and a pie chart of same data.

Android Chart Example App

In this Android chart example, we will need two separate activities, one for Bar Chart and one for Pie Chart. In the main Android activity we’ll add two buttons. On button click we’ll be directed to the respective activities.
Before we proceed, lets add MPAndroidChart library in our example chart app. Open Build.gradle app module file and paste the following code inside dependencies
compile 'com.github.PhilJay:MPAndroidChart:v2.2.4'
Now click on ‘Sync Now’. We have added library in our application successfully. Lets Build Layout of our Android app.

1. activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:gravity="center"
    android:orientation="vertical"
    tools:context="com.javapapers.androidchartapp.MainActivity">
 
    <Button
        android:id="@+id/btnBarChart"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="Bar Chart Demo" />
 
    <Button
        android:id="@+id/btnPieChart"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="Pie Chart Demo" />
 
</LinearLayout>
Now create a new empty activity and name it BarChartActivity.

2. activity_bar_chart.xml

Add the following code in layout file of BarChart activity.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical">
 
    <com.github.mikephil.charting.charts.BarChart
        android:id="@+id/barchart"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
    
</LinearLayout>
Create one more activity for Pie chart and name it PieChartActivity.

3. activity_pie_chart.xml

Paste the following to pie chart layout file.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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">
 
    <com.github.mikephil.charting.charts.PieChart
        android:id="@+id/piechart"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>
Now lets code the java files.

4. MainActivity.java

Here, we will add two buttons. We’ll set clickListeners to button and use Android Intent to launch next Activity.
package com.javapapers.androidchartapp;
 
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
 
import com.github.mikephil.charting.charts.BarChart;
 
public class MainActivity extends AppCompatActivity {
    Button btnBarChart, btnPieChart;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BarChart barChart = (BarChart) findViewById(R.id.barchart);
 
        btnBarChart = findViewById(R.id.btnBarChart);
        btnPieChart = findViewById(R.id.btnPieChart);
        btnBarChart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent I = new Intent(MainActivity.this, BarChartActivity.class);
                startActivity(I);
            }
        });
        btnPieChart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent I = new Intent(MainActivity.this, PieChartActivity.class);
                startActivity(I);
            }
        });
    }
}

5. BarChartActivity.java

We need to add data to the example Android charts. For that we will use two ArrayLists, one for year(x-axis) and another for number of employees(Y-axis). To pass data to the Android chart example we’ll need a dataset, where we will pass ArrayLists as argument.
MPAndroidChart library support various features which make Android charts attractive and appealing. To add colours to bars, i have used setColors method. To add animation, i have used animateY().
package com.javapapers.androidchartapp;
 
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
 
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;
 
import java.util.ArrayList;
 
public class BarChartActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bar_chart);
        BarChart chart = findViewById(R.id.barchart);
 
        ArrayList NoOfEmp = new ArrayList();
 
        NoOfEmp.add(new BarEntry(945f, 0));
        NoOfEmp.add(new BarEntry(1040f, 1));
        NoOfEmp.add(new BarEntry(1133f, 2));
        NoOfEmp.add(new BarEntry(1240f, 3));
        NoOfEmp.add(new BarEntry(1369f, 4));
        NoOfEmp.add(new BarEntry(1487f, 5));
        NoOfEmp.add(new BarEntry(1501f, 6));
        NoOfEmp.add(new BarEntry(1645f, 7));
        NoOfEmp.add(new BarEntry(1578f, 8));
        NoOfEmp.add(new BarEntry(1695f, 9));
 
        ArrayList year = new ArrayList();
 
        year.add("2008");
        year.add("2009");
        year.add("2010");
        year.add("2011");
        year.add("2012");
        year.add("2013");
        year.add("2014");
        year.add("2015");
        year.add("2016");
        year.add("2017");
 
        BarDataSet bardataset = new BarDataSet(NoOfEmp, "No Of Employee");
        chart.animateY(5000);
        BarData data = new BarData(year, bardataset);
        bardataset.setColors(ColorTemplate.COLORFUL_COLORS);
        chart.setData(data);
    }
}
 

6. PieChartActivty.java

Code for Android pie chart is almost same to that of bar chart. Here, again we’ll use two ArrayLists and a dataSet. We’ll add animation and colors too.
package com.javapapers.androidchartapp;
 
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
 
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.BarEntry;
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.utils.ColorTemplate;
 
import java.util.ArrayList;
 
public class PieChartActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pie_chart);
        PieChart pieChart = findViewById(R.id.piechart);
        ArrayList NoOfEmp = new ArrayList();
 
        NoOfEmp.add(new Entry(945f, 0));
        NoOfEmp.add(new Entry(1040f, 1));
        NoOfEmp.add(new Entry(1133f, 2));
        NoOfEmp.add(new Entry(1240f, 3));
        NoOfEmp.add(new Entry(1369f, 4));
        NoOfEmp.add(new Entry(1487f, 5));
        NoOfEmp.add(new Entry(1501f, 6));
        NoOfEmp.add(new Entry(1645f, 7));
        NoOfEmp.add(new Entry(1578f, 8));
        NoOfEmp.add(new Entry(1695f, 9));
        PieDataSet dataSet = new PieDataSet(NoOfEmp, "Number Of Employees");
 
        ArrayList year = new ArrayList();
 
        year.add("2008");
        year.add("2009");
        year.add("2010");
        year.add("2011");
        year.add("2012");
        year.add("2013");
        year.add("2014");
        year.add("2015");
        year.add("2016");
        year.add("2017");
        PieData data = new PieData(year, dataSet);
        pieChart.setData(data);
        dataSet.setColors(ColorTemplate.COLORFUL_COLORS);
        pieChart.animateXY(5000, 5000);
    }
}
Now lets run and test the application.

Android Chart Example Application Output

ndroid Chart Example App

Android Bar Chart Example

ndroid Chart Example Bar Chart

Android Pie Chart Example

ndroid Chart Example Pie Chart
  • https://javapapers.com/wp-content/themes/papers/images/facebook-social.png

  • https://javapapers.com/wp-content/themes/papers/images/twitter-social.png

  • https://javapapers.com/wp-content/themes/papers/images/linkedin-social.png

Popular Articles

Comments on "Android Chart Example APP using MPAndroidChart"

1.     Mavisa says:
Hi. Thanks for Great article.
what if i want to change shape of barChart to rounded bar chart?
Thanks :)
2.     Joe says:
Hi Mavisa,
As of the current moment MPAndroidChart library does not support rounded bar chart. But this feature is added to the “To-do List” for version 3.1.0
https://github.com/PhilJay/MPAndroidChart/projects/2#card-14276477
We can expect it anytime soon.

Comments

Post a Comment

Popular posts from this blog

web2apk

http://web2apk.com/create.aspx Create App   Intro   About   Changes   MalWare ?   Contact   Privacy Useful Links Bluetooth Mini Keyboards Android Mini PC Reset Android URL App Title Icon or

how to retrieve image from sqlite database in android and display in listview

 Android platform provides several ways to store data in our application. 1. SQLite database 2. SharedPreferences etc For our post, we will only work with SQLite database. First and foremost, we need to understand what an SQLite database is? SQLite database  is an open source SQL database that stores data to a text file on a device. It executes SQL Commands to perform a set of functions, that is, create, read, update and delete operations. On my previous post, I showed how to  store data in SQLite database from edit text, retrieve and populate it in a listview . For this post, I will show the SQLite CRUD operations with images from gallery and text from EditText. We need to understand this; images are stored in SQLite database as BLOB data type. A BLOB is a large binary object that can hold a variable amount of data.  Note, we can only store images in the database as BLOB data type. We need to convert our image path to a bitmap then to bytes. Also