Drawing graphs in Android using aChartEngine charting library (Line Charts)

Posted By : Ankush Gulati | 25-Jan-2013

Using Line Chart in Android

1) We will create a sample Line chart displaying two sample values set.

2) aChartEngine has the capability to show Line Chart in two ways too i.e.

   a) As a separate Activity.

   b) as a view to be embedded in current activity.

   c) we will be using the second approach, but we will be creating a new activity LineChart and then we will embed the LineChartView in that activity.

3) So, first of all, create a new android activity and name it as LineChart.

4) Now, navigate to "/res/layout" and select the xml file associated with above activity. In this case, activity_Line_chart.xml and paste the following code there.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical" android:layout_width="fill_parent"
	android:layout_height="fill_parent">	
	<LinearLayout
	    android:id="@+id/chart"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:layout_weight="0.81"
	    android:orientation="horizontal" />
</LinearLayout>
        

Notice that we have created an empty container with id "chart". This layout will contain the actual Line chart generated.

5) Now, navigate to LineChart.java file and replace the code with below code:

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

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;

public class LineChart extends Activity {
	public static final String TYPE = "type";
	private XYMultipleSeriesDataset mDataset = getDemoDataset();
	private XYMultipleSeriesRenderer mRenderer = getDemoRenderer();
	private GraphicalView mChartView;

	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_line_chart);

		setRendererStyling();
		if (mChartView == null) {
			LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
			mChartView = ChartFactory.getLineChartView(this, mDataset,
					mRenderer);
			mRenderer.setSelectableBuffer(100);
			layout.addView(mChartView, new LayoutParams(
					LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		} else
			mChartView.repaint();
	}

	private void setRendererStyling() {
		mRenderer.setApplyBackgroundColor(true);
		mRenderer.setBackgroundColor(Color.argb(100, 50, 50, 50));
		mRenderer.setAxisTitleTextSize(16);
		mRenderer.setChartTitleTextSize(20);
		mRenderer.setLabelsTextSize(15);
		mRenderer.setLegendTextSize(15);
		mRenderer.setMargins(new int[] { 20, 30, 15, 0 });
		mRenderer.setZoomButtonsVisible(true);
		mRenderer.setPointSize(10);
	}

	private XYMultipleSeriesDataset getDemoDataset() {
		double[] seriesFirstY = {20,-20,67,180,-45,24,99,-34,-8};
		double[] seriesSecondY = {10,80,-40,-20,135,24,199,-34,80};
		
		XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();

		XYSeries firstSeries = new XYSeries("Sample series One");
		for (int i = 0; i < 9; i++)
			firstSeries.add(i, seriesFirstY[i]);
		dataset.addSeries(firstSeries);

		XYSeries secondSeries = new XYSeries("Sample series Two");
		for (int j = 0; j < 9; j++)
			secondSeries.add(j, seriesSecondY[j]);
		dataset.addSeries(secondSeries);
		return dataset;
	}

	private XYMultipleSeriesRenderer getDemoRenderer() {
		XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
		renderer.setMargins(new int[] { 20, 30, 15, 0 });
		XYSeriesRenderer r = new XYSeriesRenderer();
		r.setColor(Color.BLUE);
		r.setPointStyle(PointStyle.SQUARE);
		r.setFillBelowLine(true);
		r.setFillBelowLineColor(Color.WHITE);
		r.setFillPoints(true);
		renderer.addSeriesRenderer(r);
		r = new XYSeriesRenderer();
		r.setPointStyle(PointStyle.CIRCLE);
		r.setColor(Color.GREEN);
		r.setFillPoints(true);
		renderer.addSeriesRenderer(r);
		renderer.setAxesColor(Color.DKGRAY);
		renderer.setLabelsColor(Color.LTGRAY);
		return renderer;
	}
} 

  a) The working is almost similar to the previous charts in a way that renderer and dataset are required to draw the graph and the properties associated differ.

  b) First of all, we create a demoDataset by following two sets of values:

		double[] seriesFirstY = {20,-20,67,180,-45,24,99,-34,-8};
		double[] seriesSecondY = {10,80,-40,-20,135,24,199,-34,80};
        

  We chose only Y-axis points as X-axis will be just incremented from 0 to 8.

  c) The Fx getDemoDataset() generates the Dataset according to above two series and returns the XYMultipleSeriesDataset object.

  d) Next step is to create a demoRenderer. This task is achieved pin the getDemoRenderer() function. Renderer and Dataset must contain same number of series always (2 in our case) .

  e) After this, we need to style the Renderer according to our needs such as backgroundColor, label sizes etc. We defined e method for this purpose as setRendererStyling().

  f) Now, we just need to create the actual lineChartView and embed it. So, we use the following lines in our activity's onCreate() method.

mChartView = ChartFactory.getLineChartView(this, mDataset,mRenderer);
layout.addView(mChartView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
        

6) Now, we need to start this activity. So, navigate to your activity_main.xml file and create yet another button. or paste the following code:

    <Button
        android:id="@+id/generateLineChart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="45dp"
        android:text="Generate Line Chart -->" />
        

7) Navigate to MainActivity.java file and start the LineChart activity on click of the recently created button.

Button genLineChart=(Button)findViewById(R.id.generateLineChart);
genLineChart.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				Intent lineChartIntent=new Intent(MainActivity.this,LineChart.class);
				startActivity(lineChartIntent);
			}
		});
        

8) Now, start the project in emulator or device and you will see something like following screenshot:

Hope it helps :)

Ankush Gulati

[email protected]

About Author

Author Image
Ankush Gulati

Request for Proposal

Name is required

Comment is required

Sending message..