A cunning plot

Effort-free graphs on Android with AChartEngine

DanDromereschi
achartengine1

Dan Dromereschi, creator of the popular open source AChartEngine library, shows how it can be used to quickly create line, bar and pie charts.

In
late 2008, soon after the release of Android, developers were
already looking for charting / graphing / plotting libraries. At
that time there was no such free or open-source solution
available.

I started evaluating Android for fun and after
developing a couple of Android applications that needed some
graphing, I decided I could open-source the code under the name of
AChartEngine. Version
0.2.0 was launched in March 2009, the first open-source charting
library for Android. At that time, Android SDK was at version
1.1.

Almost four years on, applications of all types are
using AChartEngine for chart rendering. The appbrain.com
Android market states that 0.53% of their total number of published
applications (over 600K), meaning that over 3000 of them are using
AChartEngine. These include Waze
and Facebook’s official
Pages manager app
.

Adding charting to an Android application with
AChartEngine, is as simple as adding the achartengine-x.y.z.jar to
the application classpath and start coding against its APIs. The
current stable version is 1.0.0 and the one under development
1.1.0. The jar file is only 110 KB is size, which is quite a small
footprint nowadays. However, despite this small size AChartEngine
offers support for many chart types.

A note on compatibility: AChartEngine supports all the Android
SDK versions from 1.6 and up. The 1.6 version offers only pan and
button based zoom, while the 2.1 and newer add support for pinch
zoom as this became available in the Android SDK 2.x and newer. A
while ago, when AChartEngine dropped the support for older Android
SDK versions than 2.1, many users asked it back in just a couple of
days after the release. At that time, according to the official
Android platform distribution available here,
there were still about 5% of devices available worldwide that were
running versions that are older than 2.x.

Features

There are three main types of charts that are supported by
AChartEngine:

  • XY charts – display data on 2 axes (line, cubic line, area,
    bar, scatter, bubble, range (high-low))
  • “Round” charts – pie, doughnut, dial
  • Combined chart – can display a combination of the XY
    charts

For a quick tour through some AChartEngine demo
application screenshots, please visit the official website and
the AChartEngine Google Code
page.

Overall Class Design

The diagram below shows the way the classes that handle the
visual rendering of the charts are organized.

  • The
    AbstractChart class describes behavior that is shared by all
    charts, including drawing background, legend, titles, etc
  • The
    XYChart class describes state and behavior that is common to
    the XY chart types like the rendering of axes, labels, etc
  • The
    RoundChart is similar to
    XYChart, but for the chart types that have a circular
    shape.

Design Components

The entire design is not limited to the visual / view part only.
There are a few more components contributing to the overall
picture.

  • The model – datasets / series of data.
  • The view – described above.
  • Renderers – help in customizing the charts appearance (colors,
    fonts, axes, labels, formatting, and so on).
  • ChartFactory – gets an instance of a dataset and an instance
    of a renderer and returns the desired chart embedded into an Intent
    (for the case when the chart fills an
    Activity) or a
    View (when the chart is a part of an
    Activity, together with other widgets).
  • Tools – interaction tools for pan and zoom.

Code Sample

In order to code against the AChartEngine APIs, you can download
one of the following binary files, include it in your classpath and
start coding:

  • Stable build, currently 1.0.0 can be downloaded here
  • Intermediate versions, release candidates can be downloaded
    here
  • Nightly builds can be downloaded
    here

Maven users can include AChartEngine in their application by
adding the following to their pom.xml file:

<repository>
    <id>achartengine</id>
    <name>Public AChartEngine repository</name>
    <url>https://repository-achartengine.forge.cloudbees.com/snapshot/</url>
</repository>

<dependency>
    <groupId>org.achartengine</groupId>
    <artifactId>achartengine</artifactId>
    <version>1.1.0</version>
</dependency>

 

The code referenced below shows an example of using AChartEngine
into an application. The program allows creating new series of data
and entering X and Y values that are then added to the current
series. The chart is updated after every addition of data. An
example of using the application to create one series of 10 data
points can be seen in the screenshot below.

The entire source code is
available here
. It includes comments for explaining the most
important parts.

The ACharEngine charting class design allows us to change one
single line of code for replacing the line chart with a bar chart.
By replacing this line:

mChartView = ChartFactory.getLineChartView(this, mDataset, mRenderer);

 

with the line below, we will get a bar chart like the one in the
following screenshot.

mChartView = ChartFactory.getBarChartView(this, mDataset, mRenderer, Type.DEFAULT);

 

Or you can replace it with the line below and have a scatter
chart instead:

mChartView = ChartFactory.getScatterChartView(this, mDataset, mRenderer);

In order to have the above example work, a simple layout file
must be defined and that will need to include a
LinearLayout with the
android:id=”@+id/chart”. The layout file for this example is

available here
.

With only some minor changes, we can reuse the code above for
building an user interface for creating pie charts. We will only
need one single input text field for entering one single value at a
time instead of the X and Y values we entered in the XY charts.
Then, we will need to instantiate another type of renderers, like
in the code below. We also need to define some color values to be
used for the slices that we create.

/** Colors to be used for the pie slices. */
private static int[] COLORS = new int[] { Color.GREEN, Color.BLUE, Color.MAGENTA, Color.CYAN };
/** The main series that will include all the data. */
private CategorySeries mSeries = new CategorySeries("");
/** The main renderer for the main dataset. */
private DefaultRenderer mRenderer = new DefaultRenderer();

 

The
onSaveInstanceState and
onRestoreInstanceState are similar to the ones in the
example above, just that this time we only save and restore the
state of the
mSeries and
mRenderer variables.

The
onCreate method is similar, except this time we can use some
renderer properties that are specific to pie charts.

// set the start angle for the first slice in the pie chart
mRenderer.setStartAngle(180);
// display values on the pie slices
mRenderer.setDisplayValues(true);

 

Under the
onClick event of the
mAdd button, we add data to the series in a similar way as
above and we add a new renderer that will handle the display of the
added slice. Then, the chart must be repainted to reflect the new
changes.

mSeries.add("Series " + (mSeries.getItemCount() + 1), value);
SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
renderer.setColor(COLORS[(mSeries.getItemCount() - 1) % COLORS.length]);
mRenderer.addSeriesRenderer(renderer);
mChartView.repaint();

 

In the
onResume() method, instead of creating a line chart view, we
build a pie chart one:

mChartView = ChartFactory.getPieChartView(this, mSeries, mRenderer);

Under the
onClick event in the chart view click listener, when the

seriesSelection is not null, meaning that there is a slice
that was selected, we want to visually highlight the selected slice
like in the screenshot below. For this, we need to set the renderer
of the selected slice as highlighted. Any visual change is
triggered by calling
repaint() on the chart view.

for (int i = 0; i < mSeries.getItemCount(); i++) {
      mRenderer.getSeriesRendererAt(i).setHighlighted(i == seriesSelection.getPointIndex());
    }
mChartView.repaint();

The resulting chart should look like this:

The code sample is included in the official demo
application that can be downloaded here.
You can find examples for all the AChartEngine supported chart
types.

Resources

You can access the official AChartEngine website here
at http://achartengine.org. There is a
Google code website providing downloadable jar, javadocs and demo
application, issue tracker and source code SVN here:  http://code.google.com/p/achartengine.

For further helpful resources, search for “AChartEngine”
on YouTube
, post questions to stackoverflow.com, chat on our
Google
group
and Facebook page or contact
us by email at contact@achartengine.org.

Ps – Contributors welcome

AChartEngine is an open-source project, so it is the result of a
community effort. Anyone interested in contributing could checkout
the source code from SVN and try to understand it. Then, take a
look at the opened issues and try fixing some of them and, when
done, provide patches.

Teaser photo by Johan
Larsson
.

Author
DanDromereschi
After spending almost five years writing radiology and imaging tools for medical software, I switched to the oil and gas industry and HPC (high-performance computing) where I am still working as a software development contractor / consultant. I always have fun designing and developing great user interfaces and 2D or 3D visualization tools, using a wide range of UI technologies like: Java Swing and SWT in desktop applications, Android in mobile, GWT, ExtGWT, ExtJS, jQueryUI on web. I always enjoyed writing charting, graphing, visualization tools using Graphics2D in Java Swing. Android canvas, HTML5 canvas, Three.js and others. See my Linkedin profile (linkedin.com/in/dandromereschi) and my software company 4viewsoft.com. When I am not in front of a computer screen, I am probably traveling, playing with my son or skiing.
Comments
comments powered by Disqus