Home > Android > Graphs on Android Using Achartengine

Graphs on Android Using Achartengine

Achartengine made life much easier in building graphs for sure. Best thing is It’s Open.
Here’s  how I got to implement a simple Bar Graph on a View.

In your Layout add a linerLayout as follows.

<LinearLayout android:id=”@+id/trendchart” android:orientation=”horizontal” android:layout_width=” fill_parent ” android:layout_height=” fill_parent ”  />

Now on your class define

For Bar Graph import the following

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.BarChart.Type;
import org.achartengine.model.CategorySeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.renderer.SimpleSeriesRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer;

private GraphicalView BarChartView;

Followed by-

if (BarChartView==null)
{
XYMultipleSeriesRenderer renderer = getBarRenderer();
setChartSettings();
BarChartView  = ChartFactory.getBarChartView(getActivity(), getBarDataset(),renderer, Type.DEFAULT);
playout.addView(BarChartView);
}
else
{
BarChartView.repaint();
BarChartView.setVisibility(View.GONE);
}

Then define your methods -

private XYMultipleSeriesRenderer getDemoRenderer()
  {
    XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
    renderer.setAxisTitleTextSize(16);
    renderer.setChartTitleTextSize(20);
    renderer.setLabelsTextSize(15);
    renderer.setLegendTextSize(15);
    renderer.setPointSize(5f);
    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;
  }

  public XYMultipleSeriesRenderer getBarDemoRenderer()
  {
    XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
    renderer.setAxisTitleTextSize(16);
    renderer.setChartTitleTextSize(20);
    renderer.setLabelsTextSize(15);
    renderer.setLegendTextSize(15);
    renderer.setBarSpacing(1);
    renderer.addXTextLabel(1, “Sun”);
    renderer.addXTextLabel(2, “Mon”);
    renderer.addXTextLabel(3, “Tue”);
    renderer.addXTextLabel(4, “Wed”);
    renderer.addXTextLabel(5, “Thu”);
    renderer.addXTextLabel(6, “Fri”);
    renderer.addXTextLabel(7, “Sat”);
    renderer.setMargins(new int[] {20, 30, 15, 0});
    SimpleSeriesRenderer r = new SimpleSeriesRenderer();
    r.setColor(Color.RED);
    renderer.addSeriesRenderer(r);
    return renderer;
  }

  private void setChartSettings(XYMultipleSeriesRenderer renderer)
  {
    renderer.setChartTitle(“Bar Chart”);
    renderer.setXTitle(“Week Days”);
    renderer.setYTitle(“Hits”);
    renderer.setXAxisMin(0);
    renderer.setXAxisMax(7);
    renderer.setYAxisMin(0);
  }

And Presto- You got a neat graph as follows-

You plenty other options too-

About these ads
Categories: Android Tags:
  1. David Cooper
    October 6, 2011 at 7:34 pm

    Is the complete project source available somewhere? I am new to android and am trying to learn how to use achartengine. I seem to be missing some pieces of the code because when I try to follow your example I get errors.

    Thank you

  2. David Cooper
    October 8, 2011 at 4:37 pm

    The first problem occurs on the line –
    XYMultipleSeriesRenderer renderer = getBarRenderer();
    getBarRenderer is not defined. On the next line setChartSettings() is defined as needing XYMultipleSeriesRenderer in the call. There are several more errors but it is hard to tell if the next ones are true errors or the result of the previous ones.
    What subroutine do the lines go?
    if (BarChartView==null)
    {
    XYMultipleSeriesRenderer renderer = getBarRenderer();
    setChartSettings();
    BarChartView = ChartFactory.getBarChartView(getActivity(), getBarDataset(),renderer, Type.DEFAULT);
    playout.addView(BarChartView);
    }
    else
    {
    BarChartView.repaint();
    BarChartView.setVisibility(View.GONE);
    }}

    I am using achartengine-0.7.0.jar

    Thank you

    • Dipmalya Majumder
      October 9, 2011 at 1:08 pm

      David,
      The above is for a bar chart using AchartEngine.
      There are 2 methods, One to define the renderer and other to set the data set.
      In my example above and below, my X coordinates are week days and Y coordinates are random numbers.
      The first method to create the renderer is as follows –

      //***************************** RENDER START*********************
      public XYMultipleSeriesRenderer getBarRenderer()
      {
      XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
      renderer.setAxisTitleTextSize(16);
      renderer.setChartTitleTextSize(20);
      renderer.setLabelsTextSize(15);
      renderer.setLegendTextSize(15);
      renderer.setBarSpacing(1);
      renderer.addXTextLabel(1, “Sun”);
      renderer.addXTextLabel(2, “Mon”);
      renderer.addXTextLabel(3, “Tue”);
      renderer.addXTextLabel(4, “Wed”);
      renderer.addXTextLabel(5, “Thu”);
      renderer.addXTextLabel(6, “Fri”);
      renderer.addXTextLabel(7, “Sat”);
      renderer.setMargins(new int[] {20, 30, 15, 0});
      SimpleSeriesRenderer r = new SimpleSeriesRenderer();
      r.setColor(Color.RED);
      r.setGradientEnabled(true);
      r.setGradientStart(-200, Color.BLUE);
      r.setGradientStop(200, 0xFFFFFFFF);
      renderer.addSeriesRenderer(r);
      return renderer;
      }
      //***************************** RENDER END *********************

      The second is to add the random data to Y
      //*********************************DATA SET START**********************
      private XYMultipleSeriesDataset getBarDataset()
      {
      XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
      Random r = new Random();
      CategorySeries series = new CategorySeries(“WeekDay series” );
      for(int i=0;i<7;i++)
      {
      series.add( 100 + r.nextInt() % 100);
      }
      dataset.addSeries(series.toXYSeries());
      return dataset;
      }

      //*********************************DATA SET END*************************

      Once you have these in place.
      Call

      "ChartFactory.getBarChartView" as below from your oncreate

      //*******************************Call BAR CHART VIEW START ****************

      XYMultipleSeriesRenderer renderer = getBarRenderer();
      setChartSettings(renderer);

      ChartFactory.getBarChartView(this, getBarDataset(), renderer, Type.DEFAULT);

      //*******************************Call BAR CHART VIEW END***************

      Hope This helps-
      Good Luck

  3. March 6, 2012 at 2:46 am

    Hi.. Nice article.
    But I want to know where the getBarDataset() method is.

  4. venki
    April 8, 2012 at 11:24 pm

    what is playout.addView(BarChartView); here

    • Dipmalya Majumder
      April 9, 2012 at 9:37 am

      Venki,
      Please refer to
      http://code.google.com/p/achartengine/
      You may wanna download a couple of ‘em and see for yourself.
      Hope this gives you more to your question.

    • priya
      May 9, 2012 at 12:14 am

      get the linear layout and add this view to it.
      LinearLayout ll = (LinearLayout) findViewById(R.id.trendchart);
      ll.addView(BarChartView);

      instead of playout.addView(BarChartView);

  5. priya
    May 28, 2012 at 8:17 pm

    How to create each bars in different colors?

    • Dipmalya Majumder
      May 30, 2012 at 10:39 am

      int start = startIndex;
      for (int row = 0; row < length; row += 2) {
      if (seriesRenderer.isMultipleColorsEnabled()) {
      paint.setColor(seriesRenderer.getColors()[start++]);
      } else {
      paint.setColor(seriesRenderer.getColor());
      }
      float x = points[row];
      float y = points[row + 1];
      drawBar(canvas, x, yAxisValue, x, y, halfDiffX, seriesNr,
      seriesIndex, paint);
      }

      Tweek it the way you want to.
      Thanks

  6. July 8, 2012 at 12:02 am

    Hi… can you please Post the full code with the XML layout and java code in a zip file.. i am very much fresher to these things… i want to implement some app in android for that i want to know how to implement BAR graph in android…
    Thanks in advance

  7. Adnan Rizve
    July 11, 2012 at 12:20 am

    @ Basu:
    XML is simple just put this in XML file:

    Instead of playout.addView(BarChartView); use these lines

    LinearLayout ll = (LinearLayout) findViewById(R.id.trendchart);
    ll.addView(BarChartView);

    Instead of XYMultipleSeriesRenderer renderer = getBarRenderer();
    Call this :
    XYMultipleSeriesRenderer renderer = getBarDemoRenderer();

    And getBarDataset() method is as follows:

    private XYMultipleSeriesDataset getBarDataset()
    {
    XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
    Random r = new Random();
    CategorySeries series = new CategorySeries(“WeekDay series” );
    for(int i=0;i<7;i++)
    {
    series.add( 100 + r.nextInt() % 100);
    }
    dataset.addSeries(series.toXYSeries());
    return dataset;
    }

  8. harish
    November 20, 2012 at 2:40 am

    If we have multiple colors in the graph where should we need to refer the particular color refers to the particular thing?And where we need to mention that coordinates.

  9. Jayant Shinde
    December 13, 2012 at 9:39 pm

    Hi how do you modify the above code to take values from a database. I am new to android and have written the following code http://stackoverflow.com/questions/13854091/chart-no-plotting but it still contains errors.

    • Dipmalya Majumder
      January 16, 2013 at 9:11 pm

      Hi Jayant. Sorry for late reply. I suggest you get your data items from the MYSQL LITE using the traditional way and put then in an arraylist. If you are not sure on android database i suggest you look into http://www.vogella.com/articles/AndroidSQLite/article.html.

  10. eriez
    April 18, 2013 at 12:43 am

    can you tell me how to connect json to achartengine ?

  11. eriez
    April 18, 2013 at 7:00 pm

    i have parse my json, ut when i want display it into linechart, nothing happen this is my source code :

    public class ErizaChartEngine extends Activity {
    List NabList = new ArrayList();
    boolean statuskoneksi= true;
    private ProgressDialog Dialog;
    protected Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    new LineChartAsyncTask().execute();
    setContentView(R.layout.layoutchart);

    }
    public class LineChartAsyncTask extends AsyncTask {

    @Override
    protected void onPreExecute (){
    super.onPreExecute();
    Dialog=new ProgressDialog(ErizaChartEngine.this);
    Dialog.setMessage(“Mohon Tunggu Sebentar…”);
    Dialog.setIndeterminate(false);
    Dialog.setCancelable(true);
    Dialog.show();
    }

    @Override
    protected String doInBackground(String… params) {
    String url= “http://www.aaaaa.cp/NabChart.htm?id=03&nilai=10″;
    try {
    JSONParser jp= new JSONParser();
    JSONArray ja= jp.takeJson(url);

    for (int i=0; i<ja.length();i++){
    JSONObject jo = ja.getJSONObject(i);
    HashMap map = new HashMap();
    if (jo.has(“lnu_nilai”))
    map.put(“lnu_nilai”, jo.get(“lnu_nilai”).toString());

    if (jo.has(“tanggal”))
    map.put(“tanggal”, jo.get(“tanggal”).toString());
    NabList.add(map);
    System.out.println(“json parser done”);

    final String strtanggal = (String)map.get(“tanggal”);
    final String strNilaiNABHMin0 = (String)map.get(“lnu_nilai”);
    drawNABContentSimpleChart(strtanggal,strNilaiNABHMin0);

    }
    }
    catch (JSONException e) {
    e.printStackTrace();
    }
    return null;
    }

    @Override
    protected void onPostExecute(String file_url) {
    Dialog.dismiss();
    }

    }

    public void drawNABContentSimpleChart
    (
    String strtanggal,
    String strNilaiNABHMin0)
    {
    XYSeries nabseries = new XYSeries(“nab”);

    for (int i=0;i<NabList.size();i++){
    nabseries.add(strNilaiNABHMin0,strtanggal);
    }
    XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
    // Adding Income Series to the dataset
    dataset.addSeries(nabseries);

    XYSeriesRenderer incomeRenderer = new XYSeriesRenderer();
    incomeRenderer.setColor(Color.WHITE);
    incomeRenderer.setPointStyle(PointStyle.CIRCLE);
    incomeRenderer.setFillPoints(true);
    incomeRenderer.setLineWidth(2);
    incomeRenderer.setDisplayChartValues(true);

    XYMultipleSeriesRenderer multiRenderer = new XYMultipleSeriesRenderer();
    multiRenderer.setXLabels(0);
    multiRenderer.setChartTitle("NAB 1 year");
    multiRenderer.setXTitle("Year 2012");
    multiRenderer.setYTitle("Nilai");
    multiRenderer.setZoomButtonsVisible(true);
    // for(int i=0;i<NabList.size();i++){
    // multiRenderer.addXTextLabel(strtanggal[i]);
    // }
    multiRenderer.addSeriesRenderer(incomeRenderer);
    // multiRenderer.addSeriesRenderer(expenseRenderer);

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

    // Start Activity
    startActivity(intent);
    }

    can you help me to show where is my fault?

  12. Anchal Mittal
    May 3, 2013 at 2:09 am

    Java Code:
    package com.example.a;

    import java.util.Random;

    import org.achartengine.ChartFactory;
    import org.achartengine.GraphicalView;
    import org.achartengine.chart.BarChart.Type;
    import org.achartengine.chart.PointStyle;
    import org.achartengine.model.CategorySeries;
    import org.achartengine.model.XYMultipleSeriesDataset;
    import org.achartengine.renderer.SimpleSeriesRenderer;
    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.View;
    import android.view.ViewGroup.LayoutParams;
    import android.widget.LinearLayout;

    public class BarChart extends Activity {

    private GraphicalView BarChartView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

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

    LinearLayout layout = (LinearLayout) findViewById(R.id.trendchart);

    if (BarChartView == null) {
    XYMultipleSeriesRenderer renderer = getBarRenderer();
    setChartSettings(renderer);
    BarChartView = ChartFactory.getBarChartView(this, getBarDataset(),
    renderer, Type.DEFAULT);
    layout.addView(BarChartView);

    } else {
    BarChartView.repaint();
    BarChartView.setVisibility(View.GONE);
    }

    }

    public XYMultipleSeriesRenderer getBarRenderer() {
    XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
    renderer.setAxisTitleTextSize(16);
    renderer.setChartTitleTextSize(20);
    renderer.setLabelsTextSize(15);
    renderer.setLegendTextSize(15);
    renderer.setBarSpacing(1);
    renderer.addXTextLabel(1, “Sun”);
    renderer.addXTextLabel(2, “Mon”);
    renderer.addXTextLabel(3, “Tue”);
    renderer.addXTextLabel(4, “Wed”);
    renderer.addXTextLabel(5, “Thu”);
    renderer.addXTextLabel(6, “Fri”);
    renderer.addXTextLabel(7, “Sat”);
    renderer.setMargins(new int[] { 20, 30, 15, 0 });
    SimpleSeriesRenderer r = new SimpleSeriesRenderer();
    r.setColor(Color.RED);
    r.setGradientEnabled(true);
    r.setGradientStart(-200, Color.BLUE);
    r.setGradientStop(200, 0xFFFFFFFF);
    renderer.addSeriesRenderer(r);
    return renderer;
    }

    private XYMultipleSeriesDataset getBarDataset() {
    XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
    Random r = new Random();
    CategorySeries series = new CategorySeries(“WeekDay series”);
    for (int i = 0; i < 7; i++) {
    series.add(100 + r.nextInt() % 100);
    }
    dataset.addSeries(series.toXYSeries());
    return dataset;
    }

    private void setChartSettings(XYMultipleSeriesRenderer renderer) {
    renderer.setChartTitle("Bar Chart");
    renderer.setXTitle("Week Days");
    renderer.setYTitle("Hits");
    renderer.setXAxisMin(0);
    renderer.setXAxisMax(7);
    renderer.setYAxisMin(0);
    }
    }

    XML Code:

  13. Anchal Mittal
    May 3, 2013 at 2:09 am

    XML Code:

  1. November 30, 2012 at 11:48 am

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 37 other followers

%d bloggers like this: