Android Drawing Bar-Chart graph using AchartEngine library

In this blog post, i’ll  explain how to draw a Bar 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.BarChart.Type;
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.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(2);
 incomeRenderer.setDisplayChartValues(true);
 incomeRenderer.setDisplayChartValuesDistance(10); //setting chart value distance 

 // Creating XYSeriesRenderer to customize expenseSeries
 XYSeriesRenderer expenseRenderer = new XYSeriesRenderer();
 expenseRenderer.setColor(Color.GREEN);
 expenseRenderer.setFillPoints(true);
 expenseRenderer.setLineWidth(2);
 expenseRenderer.setDisplayChartValues(true);

 // Creating a XYMultipleSeriesRenderer to customize the whole chart
 XYMultipleSeriesRenderer multiRenderer = new XYMultipleSeriesRenderer();
 multiRenderer.setOrientation(XYMultipleSeriesRenderer.Orientation.HORIZONTAL);
 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(false);
 //setting lines to display on x axis
 multiRenderer.setShowGridX(false);
 //setting legend to fit the screen size
 multiRenderer.setFitLegend(true);
 //setting displaying line on grid
 multiRenderer.setShowGrid(false);
 //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 max values to be display in x axis
 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);

 //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.getBarChartView(MainActivity.this, dataset, multiRenderer,Type.DEFAULT);
 //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. 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.getBarChartIntent(getBaseContext(), dataset, multiRenderer, Type.DEFAULT); 
 // Start Activity
 startActivity(intent);

and this code in the manifest file under application :

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

2. 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"

3. Here i’m using default graph to display, [i.e on line 169] This is where the graph shows one bar next to another. If you want to display a graph where one bar over the another like stack, change Type.DEFAULT to Type.STACKED. But make sure your 1st graph values [i.e incomeRenderer values] are higher than the 2nd graph [i.e expenseRenderer values], or else your 1st graph will be hidden behind the 2nd graph.

4. To rotate the graph vertical or horizontal, use this code [on line 88]

//for Horizontal
multiRenderer.setOrientation(XYMultipleSeriesRenderer.Orientation.HORIZONTAL);
//for Vertical
multiRenderer.setOrientation(XYMultipleSeriesRenderer.Orientation.VERTICAL);

But remember, default orientation is horizontal, if you didn’t specify orientation.

Sreenshot:

Horizontal Graph:
Screenshot_2014-08-12-14-52-32

 

Vertical Graph:

Screenshot_2014-12-02-14-59-33[1]

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. nitin
    • durga chiranjeevi
  2. Sunny Choudhary
    • Nagarajan
  3. Vidal
    • durga chiranjeevi
  4. ash_flash5@gmail.com
  5. sumit
  6. sumit
  7. Naveen
  8. Krunal Shah
  9. Karthikeyan

Leave a Reply

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