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

JavaFX WebView- Creating Browser Sample

Hi Friends, In this post, i am going to give an overview about JavaFX WebView . This is an embedded browser component which is based on WebKit . If allow you to use Css, JavaScript, HTML5 and more to customise your embedded browser. The embedded browser enables you to perform the following tasks in your JavaFX applications: Render HTML content from local and remote URLs Obtain Web history Execute JavaScript commands Perform upcalls from JavaScript to JavaFX Manage web pop-up windows Apply effects to the embedded browser  I am going to provide and explain you a sample example to create your embedded browser. This is a JavaFX sample example. if you want to take an introduction about JavaFX please visit my previous blog . I have use IntelliJ Idea IDE for this example. You can visit this link  to understand how to create JavaFX application. I am attaching the project structure image below- In this sample- we have two java class. First

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