Android Drawing Line Chart using AndroidPlot

October 18, 2012
By

AndroidPlot is a free and fully open source library to draw  dynamic and static graphs with in Android applications. In this article, we will create an Android application which draws an income vs expenditure line chart using AndroidPlot library.

This application is developed in Eclipse (4.2.0) with ADT plugin (20.0.3) and Android SDK ( R20.0.3 ).


1. Create a new Android application project namely “AndroidPlotDemo”

Create a new Android application project namely "AndroidPlotDemo"

Figure 1 : Create a new Android application project namely "AndroidPlotDemo"


2. Design application launcher icon

Design Application Launcher Icon

Figure 2 : Design Application Launcher Icon


3. Create a blank activity to define the class MainActivity

Create a blank activity

Figure 3 : Create a blank activity


4. Enter MainActivity details

Enter MainActivity Details

Figure 4 : Enter MainActivity Details


5. Delete Android Support Library from this project, if exists

By default Eclipse ( 4.2.0) adds Android Support Library to  Android application project. For this application, we don’t need to use this support library. So the library file libs/android-support-v4.jar may be removed manually via ProjectExplorer by simply right click on the file and then clicking the menu item “delete”.


6. Download latest stable version of AndrodPlot library ( jar file )  from  here


7. Copy the downloaded AndroidPlot library file to “libs” directory of the project


8. Update the file res/values/strings.xml


<resources>

    <string name="app_name">AndroidPlotDemo</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">AndroidPlot Demo</string>

</resources>


9. Update the layout of the MainActivity in the file res/layout/activity_main.xml


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

    <com.androidplot.xy.XYPlot
        android:id="@+id/xyplot"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        title="Income / Expenditure Chart [ Year 2012 ]"/>
</LinearLayout>


10. Update the file src/in/wptrafficanalyzer/androidplotdemo/MainActivity.java


package in.wptrafficanalyzer.androidplotdemo;

import java.text.FieldPosition;
import java.text.Format;
import java.text.ParsePosition;
import java.util.Arrays;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;

import com.androidplot.series.XYSeries;
import com.androidplot.xy.LineAndPointFormatter;
import com.androidplot.xy.SimpleXYSeries;
import com.androidplot.xy.XYPlot;
import com.androidplot.xy.XYStepMode;

public class MainActivity extends Activity {

    private XYPlot xyPlot;

    final String[] mMonths = new String[] {
        "Jan","Feb", "Mar","Apr", "May","Jun",
        "Jul", "Aug","Sep","Oct", "Nov","Dec"
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // initialize our XYPlot reference:
        xyPlot = (XYPlot) findViewById(R.id.xyplot);

        Number[] income =  {2000, 2500, 2700, 3000, 2800, 3500, 3700, 3800 };
        Number[] expense = {2200, 2700, 2900, 2800, 2600, 3000, 3300, 3400 };

        // Converting the above income array into XYSeries
        XYSeries incomeSeries = new SimpleXYSeries(
            Arrays.asList(income),                   // array => list
            SimpleXYSeries.ArrayFormat.Y_VALS_ONLY , // Y_VALS_ONLY means use the element index as the x value
            "Income");                                  // Title of this series

        // Converting the above expense array into XYSeries
        XYSeries expenseSeries = new SimpleXYSeries(
            Arrays.asList(expense),                 // array => list
            SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, // Y_VALS_ONLY means use the element index as the x value
            "Expense");                                // Title of this series

        // Create a formatter to format Line and Point of income series
        LineAndPointFormatter incomeFormat = new LineAndPointFormatter(
            Color.rgb(0, 0, 255),                   // line color
            Color.rgb(200, 200, 200),               // point color
            null );                                    // fill color (none)

        // Create a formatter to format Line and Point of expense series
        LineAndPointFormatter expenseFormat = new LineAndPointFormatter(
            Color.rgb(255, 0, 0),                   // line color
            Color.rgb(200, 200, 200),               // point color
            null);                                    // fill color (none)

        // add expense series to the xyplot:
        xyPlot.addSeries(expenseSeries,expenseFormat);

        // add income series to the xyplot:
        xyPlot.addSeries(incomeSeries, incomeFormat);

        // Formatting the Domain Values ( X-Axis )
        xyPlot.setDomainValueFormat(new Format() {

            @Override
            public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
                return new StringBuffer( mMonths[ ( (Number)obj).intValue() ]  );
            }

            @Override
            public Object parseObject(String source, ParsePosition pos) {
                return null;
            }
        });

        xyPlot.setDomainLabel("");
        xyPlot.setRangeLabel("Amount in Dollars");

        // Increment X-Axis by 1 value
        xyPlot.setDomainStep(XYStepMode.INCREMENT_BY_VAL, 1);

        xyPlot.getGraphWidget().setRangeLabelWidth(50);

        // Reduce the number of range labels
        xyPlot.setTicksPerRangeLabel(2);

        // Reduce the number of domain labels
        xyPlot.setTicksPerDomainLabel(2);

        // Remove all the developer guides from the chart
        xyPlot.disableAllMarkup();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}


11. Update the file AndroidManifest.xml


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.wptrafficanalyzer.androidplotdemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="7"
        android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        android:hardwareAccelerated="false" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>


12. Run the application

Income / Expenditure Chart using AndroidPlot in Android Application

Figure 5 : Income / Expenditure Chart using AndroidPlot in Android Application


13. Download


14. Reference

http://developer.android.com/guide/index.html


How to hire me?

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to info@wptrafficanalyzer.in.

My other blogs
store4js.blogspot.com


Android Knowledge Quiz

Ready to test your knowledge in Android? Take this quiz :



Tags: , , ,

9 Responses to Android Drawing Line Chart using AndroidPlot

  1. mimansha on February 27, 2013 at 2:19 pm

    error “Force the application to close.Try again”

  2. Burak on May 14, 2013 at 4:28 am

    Hi, Before hhanks for your sharing. But i have a question. i want to graph using database(MySql) data. how i can ?

    • edmond ochola on October 4, 2015 at 12:55 pm

      Just retrieve the data from the MySql database into an ArrayList then treat the ArrayList as an array of numbers

      • vishal Kamboj on May 31, 2016 at 10:10 pm

        hi can you give any example get data from arraylist and convert array of number to get rumtime chart and also any animation example of this plot chart

      • vishal Kamboj on June 1, 2016 at 5:58 am

        How we can push dates in x axis and arraylist in y axis any example of database.

  3. Manikandan on November 14, 2013 at 3:32 pm

    Hi,

    I like to use Barchart. How can I modify this code? Please help me.

  4. sai on November 25, 2013 at 6:24 pm

    Hi…In the X – Axis we are getting values up to july only…how should we get the entire graph upto december in X – Axis ?

    Please Help me…

  5. pedro a. on December 5, 2014 at 5:35 pm

    hello. How can i save the image?

  6. vijay chhalotre on February 12, 2015 at 4:26 pm

    I want to make graph using database(MySql) data. how i can do that?
    Thanks In Advance

Leave a Reply

Your email address will not be published. Required fields are marked *

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner