Android chart tutorial: AChartEngine
In this post, I will describe how to use AchartEngine. This is a great library for Android that help you to create charts. It supports several chart types, just to name a few:
- line chart
- area chart
- bar chart
- pie chart
- combined chart
and so on.
This library helps you in every aspects when you create a charts so you don’t need anything else to create interesting charts.
Getting started
If you use Android Studio you can download directly the jar containing all the classes and add it to your project. When the download is completed, you should add the library under libs folder so that I can be included automatically into your project. Now you are ready to use the lib!
When you create a charts you need usually a set of data that has to be drawn in the chart, in this case to have real values and to not re-invent the wheel we can suppose we get these values using WeatherLib so that we will plot the atmospheric parameters (like temperature, and pressure..).
There some basic concepts that stand behind this library and they are important so that you can use it:
- Dataset (The set of data you have to draw in your chart)
- The view (or the type of chart you want)
- Renderer (It controls how the view is drawn, settings some parameters you can change the way the charts looks like. There are two types of renderer: one that controls the rendering of the dataset and another one that controls how the main chart aspects look like (i.e. axis, labels and so on)
- Chart factory (combines the dataset and the renderers to create the charts. The chart can be created inside an Activity or the factory can return a View.)
Line chart
As first example, we want to create a Line chart. In this chart we will draw the temperature that is our Dataset. Considering that a line chart is an XY chart we create as first step the right series that holds the data:
XYSeries series = new XYSeries("London Temperature hourly");
next we have to populate the series using the data retrieved from WeatherLib (hourly weather forecast):
int hour = 0; for (HourForecast hf : nextHourForecast) { series.add(hour++, hf.weather.temperature.getTemp()); }
almost done, the series contains the data. If you look carefully we represented on X-axis the hours and on Y-axis the temperature.
Remembering the basic concepts described above, we have to create a series renderer:
// Now we create the renderer XYSeriesRenderer renderer = new XYSeriesRenderer(); renderer.setLineWidth(2); renderer.setColor(Color.RED); // Include low and max value renderer.setDisplayBoundingPoints(true); // we add point markers renderer.setPointStyle(PointStyle.CIRCLE); renderer.setPointStrokeWidth(3);
At line 3, we set the line width. One aspect you should consider when using achartengine is that the dimensions are expressed in pixel not in dp!. At line 4, we set the color and then at line 8 we set the Point Style, meaning the point contained in our series.
The last step is creating the renderer that controls the full charts and add the single renderer for each series:
XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer(); mRenderer.addSeriesRenderer(renderer);
and then:
// We want to avoid black border mRenderer.setMarginsColor(Color.argb(0x00, 0xff, 0x00, 0x00)); // transparent margins // Disable Pan on two axis mRenderer.setPanEnabled(false, false); mRenderer.setYAxisMax(35); mRenderer.setYAxisMin(0); mRenderer.setShowGrid(true); // we show the grid
A small tip: if you create a chart, you will notice that around the chart there are black borders, if you want to remove them you have to set this margin transparent (line 2). At line 5,6 we set the Y value range.
The last step is creating the View:
GraphicalView chartView = ChartFactory.getLineChartView(getActivity(), dataset, mRenderer);
Now we have the view the last step is adding it to our layout. Let us suppose we have a linear layout:
<LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/chart" android:orientation="vertical"/>
We add the view to it:
chartLyt.addView(chartView,0);
Running the example we have at the end:
Bar chart
Bar chart are another type of charts that can be built using AchartEngine. In this case, we can suppose we want to plot the pressure values retrieved from WeatherLib. As we did before we have to create a data series:
for (HourForecast hf : nextHourForecast) { series.add(hour++, hf.weather.currentCondition.getPressure()); if (hour > 24) break; }
Some steps are very similar to what explained before so we can safely jump them and create the chart:
GraphicalView chartView = ChartFactory.getBarChartView(getActivity(), dataset, mRenderer, BarChart.Type.DEFAULT);
As result we get:
Range bar
Range bar is special type of bar chart and it is interesting because it uses a different type of data series. A Range bar is a bar that has a lower and upper limit. We can use this type of chart if we want to plot the max and min temperature.
RangeCategorySeries series = new RangeCategorySeries("London next days temperature");
now we add the values:
for (DayForecast df : dayForecast) { series.add(df.forecastTemp.min, df.forecastTemp.max); mRenderer.addXTextLabel(hour++, sdf.format(df.timestamp)); }
At line 2 we set the min and max temperature adding them to the data series. At line 3 we add a label to the X-axis values. In this case we use the day number and the month:
SimpleDateFormat sdf = new SimpleDateFormat("dd,MMM");
now we add the series:
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset(); dataset.addSeries(series.toXYSeries());
and create the series renderer:
XYSeriesRenderer renderer = new XYSeriesRenderer(); renderer.setDisplayChartValues(true); mRenderer.addSeriesRenderer(renderer); mRenderer.setYAxisMax(30.0); mRenderer.setYAxisMin(0.0); renderer.setChartValuesTextSize(12); renderer.setChartValuesFormat(new DecimalFormat("#.##")); renderer.setColor(Color.GREEN);
Some aspects to notice: at line 2, we tell to the renderer we want that the values appears on the chart, while at line 6, we set the text size. Another important aspect: the value format: at line 7, we specify that we want two digits after the decimal point. Finally, we can create the graph:
GraphicalView chartView = ChartFactory.getRangeBarChartView(getActivity(), dataset, mRenderer, BarChart.Type.DEFAULT);
Running the example we have:
- Source code available soon.
Reference: | Android chart tutorial: AChartEngine from our JCG partner Francesco Azzola at the Surviving w/ Android blog. |
Hi thanks for this good example i have a question in line chart how can i scroll chart to left or right and chart update automatically ?
nice work…
now i want to move the position (0,0) to middle of the graph how can i finish it…
kindly give a code for that task..
thanks in advance.