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

Posted By : Ankush Gulati | 30-Jan-2013

In this blog, I will explain how to use charts in android in the easiest way. There are different ways to implement charts in Android such as:

1. Google Charts

2. aChartEngine charting library

3. AndroidPlot

Each comes with it's advantages and disadvantages. Like, internet is necessary if one wants to use google charts in Android app. The aChartEngine library provides support for a wide range of charts like Line, Bar and Pie etc. We will be using this library to demonstrate how to make graphs in Android. You can download the latest code and docs as well as demo app from following link: http://www.achartengine.org/  . We will be making a single project to explain all three basic types of charts.

  • Create a new Android Project, select Blank activity.

  • Create the "libs" folder under your projects root directory, if it doesn't already exist.

  • Place the achartengine's latest jar file in this "libs" folder.

  • Now, we are ready to use graphs in Android using aChartEngine.

Using Bar Charts in Android

1. We will be creating a bar chart displaying growth comparison between two companies over 10 years.

 2. aChartEngine has the capability to render and return the graph by two ways:

   a) It can return a Graph Activity.

   b) Or it can return a Graph view, which can be embedded in another activity or fragment etc.

   c) We'll be using the first approach. i.e. GraphActivity

3. So, First of all, navigate to your AndroidManifest.xml file and place following line there.

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

4. Now, navigate to your "activity_main.xml" file and place a button clicking on which will open the bar graph. Something like:

    <Button
        android:id="@+id/generatePieChart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginTop="45dp"
        android:text="Generate Pie Chart --->" />
        

5. Now it's time to actually code for Bar graph. Navigate to your MainActivity.java file and paste the below two lines in MainActivity class. These two arrays contain the sample values which will be used to draw the graph. You are free to modify or change according to requirements.

	 int[] firstData={23,145,67,78,86,190,46,78,167,164};
	 int[] secondData={83,45,168,138,67,150,64,87,144,188};
        

6. Now add the following functions in your MainActivity class.


	public void getBarChart(){
		XYMultipleSeriesRenderer barChartRenderer = getBarChartRenderer();
	    setBarChartSettings(barChartRenderer);
		Intent intent = ChartFactory.getBarChartIntent(this, getBarDemoDataset(), barChartRenderer, Type.DEFAULT);
	    startActivity(intent);
		}
	
	 private XYMultipleSeriesDataset getBarDemoDataset() {
		    XYMultipleSeriesDataset barChartDataset = new XYMultipleSeriesDataset();
				    CategorySeries firstSeries = new CategorySeries("Growth of Company1");
				    for(int i=0;i<firstData.length;i++)
				    	firstSeries.add(firstData[i]);
				    barChartDataset.addSeries(firstSeries.toXYSeries());
		    
		    	 CategorySeries secondSeries = new CategorySeries("Growth of Company2");
				    for(int j=0;j<secondData.length;j++)
				    	secondSeries.add(secondData[j]);
				    barChartDataset.addSeries(secondSeries.toXYSeries());
		    return barChartDataset;
		  }
	 
	 public XYMultipleSeriesRenderer getBarChartRenderer() {
		    XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
		    renderer.setAxisTitleTextSize(20);
		    renderer.setChartTitleTextSize(18);
		    renderer.setLabelsTextSize(18);
		    renderer.setLegendTextSize(18);
		    renderer.setMargins(new int[] {20, 30, 15, 0});
		    SimpleSeriesRenderer r = new SimpleSeriesRenderer();
		    r.setColor(Color.BLUE);
		    renderer.addSeriesRenderer(r);
		    r = new SimpleSeriesRenderer();
		    r.setColor(Color.GREEN);
		    renderer.addSeriesRenderer(r);
		    return renderer;
		  }
	 private void setBarChartSettings(XYMultipleSeriesRenderer renderer) {
		    renderer.setChartTitle("Growth comparison company1 vs company2");
		    renderer.setXTitle("No of Years in industry");
		    renderer.setYTitle("Profit in millions");
		    renderer.setXAxisMin(0.5);
		    renderer.setXAxisMax(10.5);
		    renderer.setYAxisMin(0);
		    renderer.setYAxisMax(210);
		  }
        

   a) Renderer and Dataset are two basic elements of a Graph Activity.

   b) Dataset and Renderer should have same number of series. i.e if you want to design a bar graph for two dataset comparisons, there must be two renderers.

   c) The Fx "getBarDemoDataset()" simply returns an object of XYMultipleSeriesDataset class. Since we are using two series as described in step 5, so we are creating two series and adding both series to Dataset.

   d) The Fx getBarChartRenderer() creates and returns an object of XYMultipleSeriesRenderer class defining it's specific attributes such as color of two bars and text size, margin etc.

   e) The Fx setBarChartSettings() manages the most basic characteristics of a bar chart like X or Y axis, min or max values, title to be displayed etc.

   f) The Fx getBarChart() binds all the above functions together and call for intent for Graph Activity.

   g) Organize the imports if missing.

7) Now, in your MainActivity.java file, create object of the button you created in step4 and call the getBarChart() function. Paste the following lines in onCreate() method of MainActivity:

Button genBarChart=(Button)findViewById(R.id.generateBarChart);
genBarChart.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				getBarChart();
			}
		});
        

8) Now, Run the project on emulator or device and click on "Generate Bar Chart --->" button 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..