This post describes how to implement Android chart, describing how to use AchartEngine. This is a great chart library for Android to create charts like line chart, bart chart, etc.. 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 is useful when you create Android charts and graphs. Using this Android library you don’t need anything else to create interesting charts. One possible chart is shown below:
Getting started with Android chart
If you use Android Studio to create an app using Android chart, 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!
If you prefer you can add a gradle dependency without downloading the library:
[xml] dependencies {…
compile ‘org.achartengine:achartengine:1.2.0’
}
[/xml]
When creating an Android chart, 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.)
How to create a Line chart in Android
The first Android chart we want to create is a Line chart. In this chart, it is drawn the temperature that is our Dataset. Considering that a line chart is an XY chart we create as a first step the right series that holds the data:
XYSeries series = new XYSeries("London Temperature hourly");
Moreover, we have to populate the series using the data retrieved from WeatherLib (hourly weather forecast):
[java]int hour = 0;for (HourForecast hf : nextHourForecast) {
series.add(hour++, hf.weather.temperature.getTemp());
}[/java]
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:
[java]// Now we create the rendererXYSeriesRenderer 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);[/java]
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:
[java]XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();mRenderer.addSeriesRenderer(renderer);[/java]
and then
[java]// We want to avoid black border// transparent margins
mRenderer.setMarginsColor(Color.argb(0x00, 0xff, 0x00, 0x00));
// Disable Pan on two axis
mRenderer.setPanEnabled(false, false);
mRenderer.setYAxisMax(35);
mRenderer.setYAxisMin(0);
mRenderer.setShowGrid(true); // we show the grid[/java]
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:
[java]GraphicalView chartView = ChartFactory.getLineChartView(getActivity(), dataset, mRenderer);[/java]
Now we have the view the last step is adding it to our layout. Let us suppose we have a linear layout:
[xml]<LinearLayout android:layout_width=”match_parent” android:layout_height=”match_parent” android:id=”@+id/chart” android:orientation=”vertical”/>[/xml]We add the view to it:
[java]chartLyt.addView(chartView,0);[/java]Running the example we have at the end:
Android Bar chart example
Bar chart is another type of Android 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:
[java]for (HourForecast hf : nextHourForecast) {series.add(hour++, hf.weather.currentCondition.getPressure());
if (hour > 24)
break;
}[/java]
Some steps are very similar to what explained before so we can safely jump them and create the chart:
[java]GraphicalView chartView = ChartFactory.getBarChartView(getActivity(),dataset,
mRenderer,
BarChart.Type.DEFAULT);[/java]
As result we get:
How to build Range bar in Android
Range a 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:
[java]for (DayForecast df : dayForecast) {series.add(df.forecastTemp.min, df.forecastTemp.max);
mRenderer.addXTextLabel(hour++, sdf.format(df.timestamp));
}[/java]
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 th,is case we use the day number and the month:
SimpleDateFormat sdf = new SimpleDateFormat("dd,MMM");
now we add the series:
[java]XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();dataset.addSeries(series.toXYSeries());[/java]
and create the series renderer:
[java]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);[/java]
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:
[java]GraphicalView chartView = ChartFactory.getRangeBarChartView(getActivity(), dataset,
mRenderer, BarChart.Type.DEFAULT);[/java]
Running the example we have:
At the end of this post, you know how to create charts in Android. As you have seen there are several charts available and using achartengine is possible to build easily and fast charts in Android. This library can be helpful when you have to represents some data using charts as it can happen in the weather current conditions.
is there any way to draw with animation
Draw with animation means like draw in real time?
i'm investigating it
In your linechart example, where is the dataset being loaded before it is used in chartfactory? It would be nice if you also posted the source code so we can study it. Thanks for a great tutorial.
The source code is available at github. The link is at the end of the post. Thx
I need to draw an ECG waveform using Achart engine with sampling freq-150Hz, Y axis – 1cm is 1mV & X axis- 1 cm = 4seconds. How do I modify above sample to achieve the same?
I need to draw an ECG waveform using Achart engine with sampling freq-150Hz, Y axis – 1cm is 1mV & X axis- 1 cm = 4seconds. How do I modify above sample to achieve the same?
I am sorry, I am absolute beginner and therefore I can not achieve to get this working.
Why didn’t you write where to put all these lines?
I am sorry, I am absolute beginner and therefore I can not achieve to get this working.
Why didn't you write where to put all these lines?
Hi, How to change the color of bar dynamically. let suppose i want to change the color of bar whose value is greater then 25
Hi, How to change the color of bar dynamically. let suppose i want to change the color of bar whose value is greater then 25
Why on earth wouldn’t you post which files you’re writing those lines on?
He has mentioned code is available at Github you dumb person
I have implement Week day values on x -axis from Mon to Sun. but my values are going out of screen how i manage them to set to particular screen width.
Can you send to me the source code?
Where is Area Chart? Does MP Android provides its support?
How can we set xaxis for 30 days while the keeping the maximum value as 300 days
Please reply asap
setXAxisMin and setXAxisMax
Hi, I want to plot small image in place of graph reading Point. But I can able to set only point-style. Can you please update achartengine this new feature in your new version… Thanks in advance.
Hi ,I am new to android.when i am adding the dependency in build.gradle file it is showing exception ,can u plz tell me how to do it.
Thanks, that was pretty helpful.
Hi, I’m using a line chart from this library. I have plotted all my values to the chart. But the chart doesn’t show. I did not get any error also. Kindly help.
Did you add the values?
Try go give a look at this source code https://github.com/survivingwithandroid/Surviving-with-android/blob/master/AndroidCharts/app/src/main/java/com/survivingwithandroid/charts/ChartFragment.java
Cloned from git. Not even a single chart is working.