Android Drawing Line-Chart graph using AchartEngine library

In this blog post, i’ll  explain how to draw a Line chart graph in Android using AChartEngine Library.

My Other blog on drawing charts.

  1. Bar Chart
  2. Line Chart
  3. Pie Chart
  4. Area Chart
  5. Combined Chart

 

Step 1:

Create a new project File -> Android Project. While creating a new project give activity name as MainActivity.

Step 2:

  1. Download the latest version of AChartEngine library ( jar file ) from here.
  2.  Copy the downloaded library file to “libs” directory of the project.
  3. Right click on jar file -> Build Path -> Add to Build path.

Step 3:

Open MainActivity class and copy paste this code:


import org.achartengine.ChartFactory;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.BasicStroke;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.Paint.Align;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;

public class MainActivity extends Activity {

private View mChart;
private String[] mMonth = 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);

// Getting reference to the button btn_chart
Button btnChart = (Button) findViewById(R.id.btn_chart);

// Defining click event listener for the button btn_chart
OnClickListener clickListener = new OnClickListener() {

@Override
public void onClick(View v) {
// Draw the Income vs Expense Chart
openChart();
}
};

// Setting event click listener for the button btn_chart of the MainActivity layout
btnChart.setOnClickListener(clickListener);

}

private void openChart(){
int[] x = { 0,1,2,3,4,5,6,7, 8, 9, 10, 11 };
int[] income = { 2000,2500,2700,3000,2800,3500,3700,3800, 0,0,0,0};
int[] expense = {2200, 2700, 2900, 2800, 2600, 3000, 3300, 3400, 0, 0, 0, 0 };

// Creating an XYSeries for Income
XYSeries incomeSeries = new XYSeries("Income");
// Creating an XYSeries for Expense
XYSeries expenseSeries = new XYSeries("Expense");
// Adding data to Income and Expense Series
for(int i=0;i<x.length;i++){
incomeSeries.add(i,income[i]);
expenseSeries.add(i,expense[i]);
}

// Creating a dataset to hold each series
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
// Adding Income Series to the dataset
dataset.addSeries(incomeSeries);
// Adding Expense Series to dataset
dataset.addSeries(expenseSeries);

// Creating XYSeriesRenderer to customize incomeSeries
XYSeriesRenderer incomeRenderer = new XYSeriesRenderer();
incomeRenderer.setColor(Color.CYAN); //color of the graph set to cyan
incomeRenderer.setFillPoints(true);
incomeRenderer.setLineWidth(2f);
incomeRenderer.setDisplayChartValues(true);
//setting chart value distance
incomeRenderer.setDisplayChartValuesDistance(10);
//setting line graph point style to circle
incomeRenderer.setPointStyle(PointStyle.CIRCLE);
//setting stroke of the line chart to solid
incomeRenderer.setStroke(BasicStroke.SOLID); 

// Creating XYSeriesRenderer to customize expenseSeries
XYSeriesRenderer expenseRenderer = new XYSeriesRenderer();
expenseRenderer.setColor(Color.GREEN);
expenseRenderer.setFillPoints(true);
expenseRenderer.setLineWidth(2f);
expenseRenderer.setDisplayChartValues(true);
//setting line graph point style to circle
expenseRenderer.setPointStyle(PointStyle.SQUARE);
//setting stroke of the line chart to solid
expenseRenderer.setStroke(BasicStroke.SOLID); 

// Creating a XYMultipleSeriesRenderer to customize the whole chart
XYMultipleSeriesRenderer multiRenderer = new XYMultipleSeriesRenderer();
multiRenderer.setXLabels(0);
multiRenderer.setChartTitle("Income vs Expense Chart");
multiRenderer.setXTitle("Year 2014");
multiRenderer.setYTitle("Amount in Dollars");

/***
* Customizing graphs
*/
//setting text size of the title
multiRenderer.setChartTitleTextSize(28);
//setting text size of the axis title
multiRenderer.setAxisTitleTextSize(24);
//setting text size of the graph lable
multiRenderer.setLabelsTextSize(24);
//setting zoom buttons visiblity
multiRenderer.setZoomButtonsVisible(false);
//setting pan enablity which uses graph to move on both axis
multiRenderer.setPanEnabled(false, false);
//setting click false on graph
multiRenderer.setClickEnabled(false);
//setting zoom to false on both axis
multiRenderer.setZoomEnabled(false, false);
//setting lines to display on y axis
multiRenderer.setShowGridY(true);
//setting lines to display on x axis
multiRenderer.setShowGridX(true);
//setting legend to fit the screen size
multiRenderer.setFitLegend(true);
//setting displaying line on grid
multiRenderer.setShowGrid(true);
//setting zoom to false
multiRenderer.setZoomEnabled(false);
//setting external zoom functions to false
multiRenderer.setExternalZoomEnabled(false);
//setting displaying lines on graph to be formatted(like using graphics)
multiRenderer.setAntialiasing(true);
//setting to in scroll to false
multiRenderer.setInScroll(false);
//setting to set legend height of the graph
multiRenderer.setLegendHeight(30);
//setting x axis label align
multiRenderer.setXLabelsAlign(Align.CENTER);
//setting y axis label to align
multiRenderer.setYLabelsAlign(Align.LEFT);
//setting text style
multiRenderer.setTextTypeface("sans_serif", Typeface.NORMAL);
//setting no of values to display in y axis
multiRenderer.setYLabels(10);
// setting y axis max value, Since i'm using static values inside the graph so i'm setting y max value to 4000.
// if you use dynamic values then get the max y value and set here
multiRenderer.setYAxisMax(4000);
//setting used to move the graph on xaxiz to .5 to the right
multiRenderer.setXAxisMin(-0.5);
//setting used to move the graph on xaxiz to .5 to the right
multiRenderer.setXAxisMax(11);
//setting bar size or space between two bars
//multiRenderer.setBarSpacing(0.5);
//Setting background color of the graph to transparent
multiRenderer.setBackgroundColor(Color.TRANSPARENT);
//Setting margin color of the graph to transparent
multiRenderer.setMarginsColor(getResources().getColor(R.color.transparent_background));
multiRenderer.setApplyBackgroundColor(true);
multiRenderer.setScale(2f);
//setting x axis point size
multiRenderer.setPointSize(4f);
//setting the margin size for the graph in the order top, left, bottom, right
multiRenderer.setMargins(new int[]{30, 30, 30, 30});

for(int i=0; i< x.length;i++){
multiRenderer.addXTextLabel(i, mMonth[i]);
}

// Adding incomeRenderer and expenseRenderer to multipleRenderer
// Note: The order of adding dataseries to dataset and renderers to multipleRenderer
// should be same
multiRenderer.addSeriesRenderer(incomeRenderer);
multiRenderer.addSeriesRenderer(expenseRenderer);

//this part is used to display graph on the xml
LinearLayout chartContainer = (LinearLayout) findViewById(R.id.chart);
//remove any views before u paint the chart
chartContainer.removeAllViews();
//drawing bar chart
mChart = ChartFactory.getLineChartView(MainActivity.this, dataset, multiRenderer);
//adding the view to the linearlayout
chartContainer.addView(mChart);

}

}

Step 4:

Open your activity_main.xml and copy paste this code:


<RelativeLayout 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">

 <Button
 android:id="@+id/btn_chart"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_alignParentTop="true"
 android:layout_centerHorizontal="true"
 android:layout_marginTop="33dp"
 android:text="Draw chart" />

<LinearLayout
 android:id="@+id/chart"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_alignParentBottom="true"
 android:layout_alignParentLeft="true"
 android:layout_below="@+id/btn_chart"
 tools:ignore="Orientation" >

</LinearLayout>

</RelativeLayout>

Step 5:

Create a color.xml file in the values folder and copy paste this code:


<?xml version="1.0" encoding="utf-8"?>
<resources>
 <color name="transparent_background">#00FF0000</color>
</resources>

Step 6:

In AndroidManifest.xml, No changes except declaring MainActivity(Default).


<uses-sdk
 android:minSdkVersion="8"
 android:targetSdkVersion="21" />

<application
 android:allowBackup="true"
 android:icon="@drawable/ic_launcher"
 android:label="@string/app_name"
 android:theme="@style/AppTheme" >
 <activity
 android:name=".MainActivity"
 android:label="@string/app_name"
 android:screenOrientation="portrait" >
 <intent-filter>
 <action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
 </intent-filter>
 </activity>

 </application>

 

Tips to Remember always:

1. If you read my blog on Bar chart before, then there are no major difference between bar and line chart coding. The highlighted code are the different or changed as per line chart.

2. Here i’m displaying graph in the same activity by using the view, [i.e on line 165-171]. else if you want to open in new activity i.e. achartengine graph activity, then use this code snippet:

// Creating an intent to plot bar chart using dataset and multipleRenderer
 Intent intent = ChartFactory.getLineChartIntent(getBaseContext(), dataset, multiRenderer); 
 // Start Activity
 startActivity(intent);

and this code in the manifest file under application :

<activity android:name="org.achartengine.GraphicalActivity" />

3. You can also have a background image to the chart. Insert an image in the res/drawable folder. Now open your activity_main.xml file and add this line in between 3 & 4:

android:background:"@drawable/imageName"

4. In my example, i set point style to Circle for incomeRenderer and Square for expenseRenderer[i.e on line 81 & 92]. You can change to Circle, Square, Diamond, Triangle & Point(default style).

5. In my example, i set stroke style to solid for both[i.e on line 83 & 94]. You can change to Solid, Dotted, Dashed.

 

Sreenshot:
Screenshot_2014 08 12 16 38 45

That’s it.

Hope this helpful. Your valuable comments are always welcomed. It will help to improve my post and understanding.

Download Source Code from here.

durga chiranjeevi

durga chiranjeevi

I'm currently working as Android developer at Energy Alternatives India. Interested in Application and Game development.
durga chiranjeevi
Comments
  1. neda
  2. tarun
  3. neha

Leave a Reply

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