Published on

How to use MPAndroidChart in Android Studio!

Have you ever wanted to display charts in any of your Android apps? If so, keep reading to learn how to do so!

A very complex graph by MPAndroidChart library

Figure 1: A very complex graph by MPAndroidChart library

For displaying charts in our Android applications we are going to be using the MPAndroidChart library(GitHub link here). It is a very powerful and easy to use chart library for Android. They also have an iOS version of this library, which you can find at this GitHub link.

So without further ado, let's get into this tutorial!

Setup

Firstly we will need Android Studio installed, so make sure to download and install it at this URL if you haven't already: https://developer.android.com/studio

Next, open Android Studio and create a new project with an empty activity, like so:

New Project screen

Figure 2: New Project screen

Then select whatever name and package name for this application in the following screen and click 'Finish', like so:

Final step of new project creation process

Figure 3: Final step of new project creation process

Now, we can open up the project level build.gradle file and add the following repository entry:

maven { url 'https://jitpack.io' }

Along with the following line in the module level build.gradle file:

implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0'

Development

Now with the setup out of the way, let's begin development of this simple application. Let's start out by adding a BarChart view to the res/layout/activity_main.xml layout file like so:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.github.mikephil.charting.charts.BarChart
        android:id="@+id/chart1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/seekBar1" />


</RelativeLayout>

After that we can add the programmatic logic to display this bar chart by adding the following content to the onCreate() method is our MainActivity class:

public class MainActivity extends AppCompatActivity {

    private BarChart chart;
    private SeekBar seekBarX, seekBarY;
    private TextView tvX, tvY;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);

        setTitle("BarChartActivity");


        chart.setDrawBarShadow(false);
        chart.setDrawValueAboveBar(true);

        chart.getDescription().setEnabled(false);

        // if more than 60 entries are displayed in the chart, no values will be
        // drawn
        chart.setMaxVisibleValueCount(60);

        // scaling can now only be done on x- and y-axis separately
        chart.setPinchZoom(false);

        chart.setDrawGridBackground(false);


        Legend l = chart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        l.setDrawInside(false);
        l.setForm(Legend.LegendForm.SQUARE);
        l.setFormSize(9f);
        l.setTextSize(11f);
        l.setXEntrySpace(4f);

    }
}

The above code is responsible for setting up a bar-chart instance in the main page of our simple application. For now, it won't contain any chart data, x-axis & y-axis labels and other cool features. Therefore, if we were to run the emulator to open this application, it should look like this:

MPAndroidChart's Bar Graph instance with no chart data👀

Figure 4: MPAndroidChart's Bar Graph instance with no chart data👀

Great! Now let's add some chart data to populate this bar chart by adding a new method to the MainActivity class like so:

  private void setData(int count, float range) {

        float start = 1f;

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

        for (int i = (int) start; i < start + count; i++) {
            float val = (float) (Math.random() * (range + 1));

            if (Math.random() * 100 < 25) {
                values.add(new BarEntry(i, val, getResources().getDrawable(R.drawable.star)));
            } else {
                values.add(new BarEntry(i, val));
            }
        }

        BarDataSet set1;

        if (chart.getData() != null &&
                chart.getData().getDataSetCount() > 0) {
            set1 = (BarDataSet) chart.getData().getDataSetByIndex(0);
            set1.setValues(values);
            chart.getData().notifyDataChanged();
            chart.notifyDataSetChanged();

        } else {
            set1 = new BarDataSet(values, "The year 2017");

            set1.setDrawIcons(false);

            int startColor1 = ContextCompat.getColor(this, android.R.color.holo_orange_light);
            int startColor2 = ContextCompat.getColor(this, android.R.color.holo_blue_light);
            int startColor3 = ContextCompat.getColor(this, android.R.color.holo_orange_light);
            int startColor4 = ContextCompat.getColor(this, android.R.color.holo_green_light);
            int startColor5 = ContextCompat.getColor(this, android.R.color.holo_red_light);
            int endColor1 = ContextCompat.getColor(this, android.R.color.holo_blue_dark);
            int endColor2 = ContextCompat.getColor(this, android.R.color.holo_purple);
            int endColor3 = ContextCompat.getColor(this, android.R.color.holo_green_dark);
            int endColor4 = ContextCompat.getColor(this, android.R.color.holo_red_dark);
            int endColor5 = ContextCompat.getColor(this, android.R.color.holo_orange_dark);

            List<GradientColor> gradientFills = new ArrayList<>();
            gradientFills.add(new GradientColor(startColor1, endColor1));
            gradientFills.add(new GradientColor(startColor2, endColor2));
            gradientFills.add(new GradientColor(startColor3, endColor3));
            gradientFills.add(new GradientColor(startColor4, endColor4));
            gradientFills.add(new GradientColor(startColor5, endColor5));

            set1.setGradientColors(gradientFills);

            ArrayList<IBarDataSet> dataSets = new ArrayList<>();
            dataSets.add(set1);

            BarData data = new BarData(dataSets);
            data.setValueTextSize(10f);
            data.setBarWidth(0.9f);

            chart.setData(data);
        }
    }

By the way, the above method requires a star.png image file to be used in the values.add(new BarEntry(i, val, getResources().getDrawable(R.drawable.star))); line. To download this image file just visit this Imgur link and make sure to include it in the /res/drawable folder.

Now let's give some data for our bar chart to use! To do this just append the following line to the end of onCreate() method:

@Override
protected void onCreate(Bundle savedInstanceState) {

    ...
    setData(5, 100);
}

Then if you fire up the emulator by clicking the 'Run App' button towards the top right of the screen you should be presented with something similar to this screenshot:

MPAndroidChart's Bar Graph instance with data😎

Figure 5: MPAndroidChart's Bar Graph instance with data😎

And voila! The setupData() method has populated our bar graph with randomized data. And with that we can end this basic tutorial on how to use the MPAndroidChart library in Android applications.

Conclusion

Congratulations! You now know how to use the MPAndroidChart library in Android applications. If you need access to the source code for this application you can access it by visiting it's GitHub link.

Well that's it for this post! Thanks for following along in this article and if you have any questions or concerns please feel free to post a comment in this post and I will get back to you when I find the time.

If you found this article helpful please share it and make sure to follow me on Twitter and GitHub, connect with me on LinkedIn and subscribe to my YouTube channel.