Skip to main content

Working with MPAndroidChart (how to create Bar Chart using MPAndroidChart)

Hi Friends,

In this tutorial i am going to show, "How to create Bar Chart using MPAndroidChart". There is a lot of libraries for creating charts in android like AChartEngine, MpAndroidChart, AndroidPlot etc.
Your first question may be, Why MPAndroidChart. So MpAndroidChart provides better animation functionality and easy to use in comparision.

Using MPAndroidChart library we can draw a:
·         Simple Bar Chart
·         Grouped Bar Chart
·         Horizontal Bar Chart
·         Simple Line Chart
·         Line Chart with Cubic Lines
·         Grouped Line Chart
·         Combined Line and Bar Chart
·         Pie Chart
·         Scatter Chart
·         Candlestick Chart
·         Radar Chart
Here we will create Simple Bar Chart with multiple color based on ranging.



Ok We start with coding part now.

First of all create your project in Android Studio and add gradle dependency for MPAndroidChart library into your build.gradle file under <your-project>/app/build.gradle.

compile 'com.github.PhilJay:MPAndroidChart:v2.0.9'

And add repository after dependencies.

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

Now In your MainActivity.java copy and paste following code:-

MainActivity.java

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatButton;
import android.view.View;

import com.droidamar.mpandroidchartdemo.R;
import com.droidamar.mpandroidchartdemo.util.MPUtil;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.data.BarData;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private BarChart chart;
    private AppCompatButton btnXAnimation, btnYAnimation, btnXYAnimation;

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

        init();

        Random r = new Random();
        List<Float> dataList = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            dataList.add((float) (r.nextInt(300 - 25) + 25));
        }

        BarData barData2 = new BarData(MPUtil.getXAxisValues(20), 

        MPUtil.getDataSet(MainActivity.this, dataList));
        MPUtil.drawChart(MainActivity.this, chart, barData2);

        btnXAnimation.setOnClickListener(this);
        btnYAnimation.setOnClickListener(this);
        btnXYAnimation.setOnClickListener(this);
    }

    private void init() {
        chart = (BarChart) findViewById(R.id.chart);
        btnXAnimation = (AppCompatButton) findViewById(R.id.btnXAnimation);
        btnYAnimation = (AppCompatButton) findViewById(R.id.btnYAnimation);
        btnXYAnimation = (AppCompatButton) findViewById(R.id.btnXYAnimation);
    }

    @Override    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnXAnimation:
                chart.animateX(3000);
                break;
            case R.id.btnYAnimation:
                chart.animateY(3000);
                break;
            case R.id.btnXYAnimation:
                chart.animateXY(3000, 3000);
                break;
        }
    }
}


Create an util package and create a class named MyBarDataSet.java and MPUtil.java

MyBarDataSet.java class used to fill multiple color to bar set, ranging for specified data i.e if chart
value is less than or equal to  50, 0th color will be paint and so on...

MyBarDataSet.java

import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;

import java.util.List;

public class MyBarDataSet extends BarDataSet {


    public MyBarDataSet(List<BarEntry> yVals, String label) {
        super(yVals, label);
    }

    @Override    public int getColor(int index)
    {
        float indexVal = getEntryForXIndex(index).getVal();

        if (indexVal <= 50)
            return mColors.get(0);
        else if (indexVal > 50 && indexVal <= 150)
            return mColors.get(1);
        else if (indexVal > 150 && indexVal <= 300)
            return mColors.get(2);
        else            return mColors.get(3);
    }

}

MPUtil.java class contains core method named drawChart(...) which in responsible for drawing chart.

MPUtil.java

import android.content.Context;

import com.droidamar.mpandroidchartdemo.R;
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;
import java.util.List;

public class MPUtil {

    private static int textSize = 10;

    public static ArrayList<BarDataSet> getDataSet(Context context, List<Float> dataList) {

        ArrayList<BarDataSet> dataSets = new ArrayList<>();

        ArrayList<BarEntry> valueSet = new ArrayList<>();

        for (int i = 0; i < dataList.size(); i++) {
            valueSet.add(new BarEntry(dataList.get(i), i));
        }
        int[] colors = {context.getResources().getColor(R.color.color1),
                context.getResources().getColor(R.color.color2),
                context.getResources().getColor(R.color.color3),
                context.getResources().getColor(R.color.color4)};

        BarDataSet barDataSet = new MyBarDataSet(valueSet, "");
        barDataSet.setColors(colors);
        barDataSet.setValueTextSize(textSize);
        barDataSet.setBarSpacePercent(30);

        dataSets.add(barDataSet);

        return dataSets;
    }

    public static ArrayList<String> getXAxisValues(int dataSize) {

        ArrayList<String> xAxis = new ArrayList<>();

        for (int i = 0; i < dataSize; i++) {
            xAxis.add(String.valueOf(i + 1));
        }
        return xAxis;
    }

//this is the main method which draw the chart   

 public static void drawChart(final Context context, BarChart chart, BarData data) {
        XAxis xAxis = chart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);

        xAxis.setDrawLabels(true);
        xAxis.setDrawAxisLine(true);
        xAxis.setAxisLineWidth(2);  // x ashix line size 

        xAxis.setAxisLineColor(context.getResources().getColor(android.R.color.white));
        xAxis.setDrawGridLines(false);
        xAxis.setTextSize(textSize);
        xAxis.setTextColor(context.getResources().getColor(android.R.color.white));

        chart.getAxisRight().setDrawAxisLine(false);
        chart.getAxisRight().setDrawGridLines(false);
        chart.getAxisRight().setDrawLabels(false);

        YAxis yAxis = chart.getAxisLeft();
        yAxis.setDrawGridLines(false);
        yAxis.setTextSize(textSize);
        yAxis.setTextColor(context.getResources().getColor(android.R.color.white));
        yAxis.setAxisLineColor(context.getResources().getColor(android.R.color.white));
        yAxis.setAxisLineWidth(2);  // y ashix line size
        data.setValueTextColor(context.getResources().getColor(android.R.color.white)); //        bar data level        

        data.setValueTextSize(12); // bar data size
        // bar data size
        chart.setData(data);
        chart.setDescription("");
        chart.invalidate();
        chart.setHorizontalScrollBarEnabled(true);
        chart.setVisibleXRange(8);
        chart.getLegend().setEnabled(false);
        chart.setDrawGridBackground(false);
        chart.setDoubleTapToZoomEnabled(false);
    }

}

Your colors.xml file should be like this:-

<?xml version="1.0" encoding="utf-8"?><resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>

    <color name="color1">#47b629</color>
    <color name="color2">#5fd8fb</color>
    <color name="color3">#f7ae11</color>
    <color name="color4">#FB741A</color>
    <color name="color5">#fb3f1a</color>

</resources>


This is all about drawing a bar chart using MPAndroidChart in android. You can download complete source code from this github link.

Suggestions are most welcome. Please keep reading my blog and share to your friends :)

Thanks for visiting me)




Comments

Popular posts from this blog

app-policy

PRIVACY POLICY Last updated April 19, 2023 This privacy notice for Team CoderzDuniya ( " Company ," " we ," " us ," or " our " ), describes how and why we might collect, store, use, and/or share ( " process " ) your information when you use our services ( " Services " ), such as when you: Download and use our mobile application ( Revenue Calculator) , or any other application of ours that links to this privacy notice Engage with us in other related ways, including any sales, marketing, or events Questions or concerns?  Reading this privacy notice will help you understand your privacy rights and choices. If you do not agree with our policies and practices, please do not use our Services. If you still have any questions or concerns, please contact us at droidamar007@gmail.com . SUMMARY OF KEY POINTS This summary provides key points from our privacy notice, but you can find out more details about any of these t...

Java Socket Basics(Socket Programming in Java) Part-2(UDP)

Hi friends, We are going to discuss about UDP Socket Programming . In previous post  we discussed about the differences between TCP & UDP and the sample example of TCP Socket Programming. Below is the sample example of chat application using UDP  Socket Programming . UDP Sample :-  We are going to create an small example which contains two classes. UdpServer.java:-  This is a server class. Means this class will serve the purpose of socket connection. DatagramSocket is the java class and serve the purpose of Server and Client both. The overloaded constructor of DatagramSocket class matters. DatagramPacket is the java class which is responsible to transmit the data/packet over the network from server to client and vice-versa. UdpClient.java:-  This is client class. This serves the purpose of client which will communicate to server and send data to server and receive the data sent by server. UdpServer.java import java.net.DatagramPac...

Inline editable table-row using the edit button in Angular

In this tutorial, we will see an example of inline-editable rows of a table using mat-table. To create an  inline editable table row  using the  MatTable  component in Angular, you will need to use Angular Material ( @angular/material ) for UI components, along with Angular's built-in data binding to manage the state of each row when the user clicks the  Edit  button. Here's a step-by-step guide to implement this: Step 1: Set Up Angular Material First, you need to install Angular Material in your project. If you haven't already, run the following commands: ng add @angular/material During the installation, you will be prompted to select a theme and some other configuration options. You can choose the default options for now. Step 2: Install Required Angular Material Modules Next, you need to import the relevant Angular Material modules. Open your  app.module.ts  and import the necessary Material components: import { NgModule } from '@angular/core'...