SlideShare a Scribd company logo
1 of 11
"Android Application Development Company India" www.letsnurture.com
Draw Graph using Chart engine
Library
"Android Application Development Company India" www.letsnurture.com
Draw Graph using Chart engine Library
Follow Simple steps to draw chart like
 line chart
 area chart
 scatter chart
 time chart
 bar chart
 pie chart
 bubble chart
 doughnut chart
 range (high-low) bar chart
 dial chart / gauge
 combined (any combination of line, cubic line, scatter, bar, range bar, bubble) chart
 cubic line chart
Link to Examle
Here example of Line Chart
step 1:
download A-Chart Engine library from this link. copy the jar file into the libs folder of your
project.
step 2
the activity_main.xml like the following:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
"Android Application Development Company India" www.letsnurture.com
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/Chart_layout"
android:orientation="vertical">
</LinearLayout>
</LinearLayout>
step 3
In the main.java do the following steps.
// First Create a Graphical View object called mChart.
import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.BasicStroke;
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.Menu;
"Android Application Development Company India" www.letsnurture.com
import android.widget.LinearLayout;
public class MainActivity extends Activity {
private GraphicalView 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);
openChart();
}
private void openChart() {
int[] x = { 1, 2, 3, 4, 5, 6, 7, 8 };
int[] income = { 2000, 2500, 2700, 3000, 2800, 3500, 3700, 3800 };
// int[] margin = { 10, -10, 10, 10 };
int[] expense = { 2200, 2200, 2200, 2200, 2200, 2200, 2200, 2200 };
// Creating an XYSeries for Performance
XYSeries performanceSeries = new XYSeries("Perfomance");
XYSeries expenseSeries = new XYSeries("expense");
// Adding data to Income and Expense Series
for (int i = 0; i < x.length; i++) {
performanceSeries.add(x[i], income[i]);
expenseSeries.add(x[i], expense[i]);
}
// Creating a dataset to hold each series
"Android Application Development Company India" www.letsnurture.com
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
// Adding Perfomance Series to the dataset
dataset.addSeries(performanceSeries);
dataset.addSeries(expenseSeries);
// Creating XYSeriesRenderer to customize/style performanceSeries
XYSeriesRenderer performanceRenderer = new XYSeriesRenderer();
performanceRenderer.setColor(Color.GREEN);
performanceRenderer.setPointStyle(PointStyle.TRIANGLE);
performanceRenderer.setFillPoints(true);
performanceRenderer.setStroke(BasicStroke.SOLID);
performanceRenderer.setLineWidth(2);
performanceRenderer.setDisplayChartValues(true);
// Creating second XYSeriesRenderer to customize/style performanceSeries
XYSeriesRenderer expenseRenderer = new XYSeriesRenderer();
expenseRenderer.setColor(Color.YELLOW);
expenseRenderer.setPointStyle(PointStyle.TRIANGLE);
expenseRenderer.setFillPoints(true);
expenseRenderer.setStroke(BasicStroke.SOLID);
expenseRenderer.setLineWidth(2);
expenseRenderer.setDisplayChartValues(true);
// Creating a XYMultipleSeriesRenderer to customize the whole chart
XYMultipleSeriesRenderer multiRenderer = new XYMultipleSeriesRenderer();
multiRenderer.setXLabels(-15);
multiRenderer.setLabelsTextSize(20);
multiRenderer.setAxisTitleTextSize(30);
// add chart title and x and y title
multiRenderer.setChartTitle("Performance Chart");
multiRenderer.setXTitle("Performance X title");
"Android Application Development Company India" www.letsnurture.com
multiRenderer.setYTitle("Performance Y Title");
// multiRenderer.setZoomButtonsVisible(true);
for (int i = 0; i < x.length; i++) {
multiRenderer.addXTextLabel(i + 1, 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(performanceRenderer);
multiRenderer.addSeriesRenderer(expenseRenderer);
// Getting a reference to LinearLayout of the MainActivity Layout
LinearLayout chartContainer = (LinearLayout) findViewById(R.id.chart_container);
// Creating a Line Chart
mChart = (GraphicalView) ChartFactory.getLineChartView(
getBaseContext(), dataset, multiRenderer);
// Adding the Line Chart to the LinearLayout
chartContainer.addView(mChart);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Finally You will get a Line Chart that will look like this.
"Android Application Development Company India" www.letsnurture.com
Here example of Pie Chart
step 1:
create a new android activity and name it as PieChart.
Step 2:
Now, navigate to "/res/layout" and select the xml file associated with above activity. In this case,
activity_pie_chart.xml and paste the following code there.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout android:id="@+id/chart"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
step 3:
"Android Application Development Company India" www.letsnurture.com
Now, navigate to PieChart.java file and replace the code with below code
import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.model.CategorySeries;
import org.achartengine.renderer.DefaultRenderer;
import org.achartengine.renderer.SimpleSeriesRenderer;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
public class PieChart extends Activity {
int[] pieChartValues={25,15,20,40};
publics tatic final String TYPE = "type";
private static int[] COLORS = new int[] { Color.GREEN, Color.BLUE,
Color.MAGENTA, Color.CYAN };
private CategorySeries mSeries = new CategorySeries("");
private DefaultRenderer mRenderer = new DefaultRenderer();
"Android Application Development Company India" www.letsnurture.com
private GraphicalView mChartView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pie_chart);
mRenderer.setApplyBackgroundColor(true);
mRenderer.setBackgroundColor(Color.argb(100,50,50,50));
mRenderer.setChartTitleTextSize(20);
mRenderer.setLabelsTextSize(15);
mRenderer.setLegendTextSize(15);
mRenderer.setMargins(new int[] {20,30,15,0});
mRenderer.setZoomButtonsVisible(true);
mRenderer.setStartAngle(90);
if (mChartView == null) {
LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
mChartView = ChartFactory.getPieChartView(this, mSeries, mRenderer);
mRenderer.setClickEnabled(true);
mRenderer.setSelectableBuffer(10);
layout.addView(mChartView, new
LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
} else {
mChartView.repaint();
}
fillPieChart();
}
"Android Application Development Company India" www.letsnurture.com
public void fillPieChart(){
for(int i=0;i<pieChartValues.length;i++)
{
mSeries.add(" Share Holder "+ (mSeries.getItemCount() + 1),
pieChartValues[i]);
SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
renderer.setColor(COLORS[(mSeries.getItemCount() -1) %
COLORS.length]);
mRenderer.addSeriesRenderer(renderer);
if (mChartView != null)
mChartView.repaint();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
The working of code is almost similar to that of Bar chart. Renderer is used to actually draw the Pie
chart and we created a Dataset as a sample array
"Android Application Development Company India" www.letsnurture.com
int[] pieChartValues={25,15,20,40};
Then, we declare the different colors which will be used the differentiate the graph area. In our case
private static int[] COLORS = new int[] { Color.GREEN, Color.BLUE,
Color.MAGENTA, Color.CYAN };
Then we have to declare some basic characteristics for renderer such as title, title size, margin,
zoom option or start angle etc. You can always modify it as per requirements. Since we are using
another activity to display the Pie chart so we declare it in onCreate method of PieChart activity.
Then we actually create reference of the "chart" layout we created in step 4 and assign the
"chartView" to it and call the fillPieChart() method.
if (mChartView == null) {
LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
mChartView = ChartFactory.getPieChartView(this, mSeries, mRenderer);
mRenderer.setClickEnabled(true);
mRenderer.setSelectableBuffer(10);
layout.addView(mChartView, new
LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
} else {
mChartView.repaint();
}
fillPieChart();
}
Link of Source Code

More Related Content

Viewers also liked

Viewers also liked (13)

Basic business statistics 2
Basic business statistics 2Basic business statistics 2
Basic business statistics 2
 
Workplace Engagement Survey - Presentation
Workplace Engagement Survey - PresentationWorkplace Engagement Survey - Presentation
Workplace Engagement Survey - Presentation
 
How to Write a One-Page Abstract
How to Write a One-Page AbstractHow to Write a One-Page Abstract
How to Write a One-Page Abstract
 
IELTS ACADEMIC TASK 1: How to describe a pie chart
IELTS ACADEMIC TASK 1: How to describe a pie chartIELTS ACADEMIC TASK 1: How to describe a pie chart
IELTS ACADEMIC TASK 1: How to describe a pie chart
 
#Instagram API Get visibility you always wanted
#Instagram API   Get visibility you always wanted#Instagram API   Get visibility you always wanted
#Instagram API Get visibility you always wanted
 
материал к тесту 6 класс
материал к тесту 6 классматериал к тесту 6 класс
материал к тесту 6 класс
 
Dna
DnaDna
Dna
 
Holes (themes)
Holes (themes)Holes (themes)
Holes (themes)
 
Marshall Cassidy : VOCALSpin : My Dream Girl
Marshall Cassidy : VOCALSpin : My Dream GirlMarshall Cassidy : VOCALSpin : My Dream Girl
Marshall Cassidy : VOCALSpin : My Dream Girl
 
Final
FinalFinal
Final
 
Инвестиции в 9 шагов
Инвестиции в 9 шаговИнвестиции в 9 шагов
Инвестиции в 9 шагов
 
Changing the culture of it
Changing the culture of itChanging the culture of it
Changing the culture of it
 
Pil-educational art software designed by Miss Munrakhan
Pil-educational art software designed by Miss MunrakhanPil-educational art software designed by Miss Munrakhan
Pil-educational art software designed by Miss Munrakhan
 

More from Ketan Raval

Android notifications
Android notificationsAndroid notifications
Android notifications
Ketan Raval
 

More from Ketan Raval (20)

Amazon Alexa Auto Software Development Kit (SDK)
Amazon Alexa Auto Software Development Kit (SDK)Amazon Alexa Auto Software Development Kit (SDK)
Amazon Alexa Auto Software Development Kit (SDK)
 
Proximity Marketing Solutions enhancing Businesses leveraging iBeacon SDK Int...
Proximity Marketing Solutions enhancing Businesses leveraging iBeacon SDK Int...Proximity Marketing Solutions enhancing Businesses leveraging iBeacon SDK Int...
Proximity Marketing Solutions enhancing Businesses leveraging iBeacon SDK Int...
 
Keynote 2016
Keynote 2016Keynote 2016
Keynote 2016
 
Zero ui future is here
Zero ui   future is hereZero ui   future is here
Zero ui future is here
 
Android n and beyond
Android n and beyondAndroid n and beyond
Android n and beyond
 
IoT and Future of Connected world
IoT and Future of Connected worldIoT and Future of Connected world
IoT and Future of Connected world
 
Keynote - Devfest 2015 organized by GDG Ahmedabad
Keynote - Devfest 2015 organized by GDG AhmedabadKeynote - Devfest 2015 organized by GDG Ahmedabad
Keynote - Devfest 2015 organized by GDG Ahmedabad
 
Android notifications
Android notificationsAndroid notifications
Android notifications
 
How to make your Mobile App HIPPA Compliant
How to make your Mobile App HIPPA CompliantHow to make your Mobile App HIPPA Compliant
How to make your Mobile App HIPPA Compliant
 
3 d touch a true game changer
3 d touch a true game changer3 d touch a true game changer
3 d touch a true game changer
 
OBD Mobile App - Fault Codes, Driving Behaviour and Fuel Economy
OBD Mobile App - Fault Codes, Driving Behaviour and Fuel EconomyOBD Mobile App - Fault Codes, Driving Behaviour and Fuel Economy
OBD Mobile App - Fault Codes, Driving Behaviour and Fuel Economy
 
Vehicle to vehicle communication using gps
Vehicle to vehicle communication using gpsVehicle to vehicle communication using gps
Vehicle to vehicle communication using gps
 
Obd how to guide
Obd how to guideObd how to guide
Obd how to guide
 
Garmin api integration
Garmin api integrationGarmin api integration
Garmin api integration
 
Beacon The Google Way
Beacon The Google WayBeacon The Google Way
Beacon The Google Way
 
Edge detection iOS application
Edge detection iOS applicationEdge detection iOS application
Edge detection iOS application
 
Google calendar integration in iOS app
Google calendar integration in iOS appGoogle calendar integration in iOS app
Google calendar integration in iOS app
 
Big data cloudcomputing
Big data cloudcomputingBig data cloudcomputing
Big data cloudcomputing
 
All about Apple Watchkit
All about Apple WatchkitAll about Apple Watchkit
All about Apple Watchkit
 
How to upload application on iTune store
How to upload application on iTune storeHow to upload application on iTune store
How to upload application on iTune store
 

Recently uploaded

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 

Graph for Pie chart and Line Chart in Android Development

  • 1. "Android Application Development Company India" www.letsnurture.com Draw Graph using Chart engine Library
  • 2. "Android Application Development Company India" www.letsnurture.com Draw Graph using Chart engine Library Follow Simple steps to draw chart like  line chart  area chart  scatter chart  time chart  bar chart  pie chart  bubble chart  doughnut chart  range (high-low) bar chart  dial chart / gauge  combined (any combination of line, cubic line, scatter, bar, range bar, bubble) chart  cubic line chart Link to Examle Here example of Line Chart step 1: download A-Chart Engine library from this link. copy the jar file into the libs folder of your project. step 2 the activity_main.xml like the following: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"
  • 3. "Android Application Development Company India" www.letsnurture.com android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/Chart_layout" android:orientation="vertical"> </LinearLayout> </LinearLayout> step 3 In the main.java do the following steps. // First Create a Graphical View object called mChart. import org.achartengine.ChartFactory; import org.achartengine.GraphicalView; import org.achartengine.chart.PointStyle; import org.achartengine.model.XYMultipleSeriesDataset; import org.achartengine.model.XYSeries; import org.achartengine.renderer.BasicStroke; 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.Menu;
  • 4. "Android Application Development Company India" www.letsnurture.com import android.widget.LinearLayout; public class MainActivity extends Activity { private GraphicalView 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); openChart(); } private void openChart() { int[] x = { 1, 2, 3, 4, 5, 6, 7, 8 }; int[] income = { 2000, 2500, 2700, 3000, 2800, 3500, 3700, 3800 }; // int[] margin = { 10, -10, 10, 10 }; int[] expense = { 2200, 2200, 2200, 2200, 2200, 2200, 2200, 2200 }; // Creating an XYSeries for Performance XYSeries performanceSeries = new XYSeries("Perfomance"); XYSeries expenseSeries = new XYSeries("expense"); // Adding data to Income and Expense Series for (int i = 0; i < x.length; i++) { performanceSeries.add(x[i], income[i]); expenseSeries.add(x[i], expense[i]); } // Creating a dataset to hold each series
  • 5. "Android Application Development Company India" www.letsnurture.com XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset(); // Adding Perfomance Series to the dataset dataset.addSeries(performanceSeries); dataset.addSeries(expenseSeries); // Creating XYSeriesRenderer to customize/style performanceSeries XYSeriesRenderer performanceRenderer = new XYSeriesRenderer(); performanceRenderer.setColor(Color.GREEN); performanceRenderer.setPointStyle(PointStyle.TRIANGLE); performanceRenderer.setFillPoints(true); performanceRenderer.setStroke(BasicStroke.SOLID); performanceRenderer.setLineWidth(2); performanceRenderer.setDisplayChartValues(true); // Creating second XYSeriesRenderer to customize/style performanceSeries XYSeriesRenderer expenseRenderer = new XYSeriesRenderer(); expenseRenderer.setColor(Color.YELLOW); expenseRenderer.setPointStyle(PointStyle.TRIANGLE); expenseRenderer.setFillPoints(true); expenseRenderer.setStroke(BasicStroke.SOLID); expenseRenderer.setLineWidth(2); expenseRenderer.setDisplayChartValues(true); // Creating a XYMultipleSeriesRenderer to customize the whole chart XYMultipleSeriesRenderer multiRenderer = new XYMultipleSeriesRenderer(); multiRenderer.setXLabels(-15); multiRenderer.setLabelsTextSize(20); multiRenderer.setAxisTitleTextSize(30); // add chart title and x and y title multiRenderer.setChartTitle("Performance Chart"); multiRenderer.setXTitle("Performance X title");
  • 6. "Android Application Development Company India" www.letsnurture.com multiRenderer.setYTitle("Performance Y Title"); // multiRenderer.setZoomButtonsVisible(true); for (int i = 0; i < x.length; i++) { multiRenderer.addXTextLabel(i + 1, 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(performanceRenderer); multiRenderer.addSeriesRenderer(expenseRenderer); // Getting a reference to LinearLayout of the MainActivity Layout LinearLayout chartContainer = (LinearLayout) findViewById(R.id.chart_container); // Creating a Line Chart mChart = (GraphicalView) ChartFactory.getLineChartView( getBaseContext(), dataset, multiRenderer); // Adding the Line Chart to the LinearLayout chartContainer.addView(mChart); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } } Finally You will get a Line Chart that will look like this.
  • 7. "Android Application Development Company India" www.letsnurture.com Here example of Pie Chart step 1: create a new android activity and name it as PieChart. Step 2: Now, navigate to "/res/layout" and select the xml file associated with above activity. In this case, activity_pie_chart.xml and paste the following code there. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:id="@+id/chart" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1" /> </LinearLayout> step 3:
  • 8. "Android Application Development Company India" www.letsnurture.com Now, navigate to PieChart.java file and replace the code with below code import org.achartengine.ChartFactory; import org.achartengine.GraphicalView; import org.achartengine.model.CategorySeries; import org.achartengine.renderer.DefaultRenderer; import org.achartengine.renderer.SimpleSeriesRenderer; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.view.Menu; import android.view.ViewGroup.LayoutParams; import android.widget.LinearLayout; public class PieChart extends Activity { int[] pieChartValues={25,15,20,40}; publics tatic final String TYPE = "type"; private static int[] COLORS = new int[] { Color.GREEN, Color.BLUE, Color.MAGENTA, Color.CYAN }; private CategorySeries mSeries = new CategorySeries(""); private DefaultRenderer mRenderer = new DefaultRenderer();
  • 9. "Android Application Development Company India" www.letsnurture.com private GraphicalView mChartView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pie_chart); mRenderer.setApplyBackgroundColor(true); mRenderer.setBackgroundColor(Color.argb(100,50,50,50)); mRenderer.setChartTitleTextSize(20); mRenderer.setLabelsTextSize(15); mRenderer.setLegendTextSize(15); mRenderer.setMargins(new int[] {20,30,15,0}); mRenderer.setZoomButtonsVisible(true); mRenderer.setStartAngle(90); if (mChartView == null) { LinearLayout layout = (LinearLayout) findViewById(R.id.chart); mChartView = ChartFactory.getPieChartView(this, mSeries, mRenderer); mRenderer.setClickEnabled(true); mRenderer.setSelectableBuffer(10); layout.addView(mChartView, new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT)); } else { mChartView.repaint(); } fillPieChart(); }
  • 10. "Android Application Development Company India" www.letsnurture.com public void fillPieChart(){ for(int i=0;i<pieChartValues.length;i++) { mSeries.add(" Share Holder "+ (mSeries.getItemCount() + 1), pieChartValues[i]); SimpleSeriesRenderer renderer = new SimpleSeriesRenderer(); renderer.setColor(COLORS[(mSeries.getItemCount() -1) % COLORS.length]); mRenderer.addSeriesRenderer(renderer); if (mChartView != null) mChartView.repaint(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } } The working of code is almost similar to that of Bar chart. Renderer is used to actually draw the Pie chart and we created a Dataset as a sample array
  • 11. "Android Application Development Company India" www.letsnurture.com int[] pieChartValues={25,15,20,40}; Then, we declare the different colors which will be used the differentiate the graph area. In our case private static int[] COLORS = new int[] { Color.GREEN, Color.BLUE, Color.MAGENTA, Color.CYAN }; Then we have to declare some basic characteristics for renderer such as title, title size, margin, zoom option or start angle etc. You can always modify it as per requirements. Since we are using another activity to display the Pie chart so we declare it in onCreate method of PieChart activity. Then we actually create reference of the "chart" layout we created in step 4 and assign the "chartView" to it and call the fillPieChart() method. if (mChartView == null) { LinearLayout layout = (LinearLayout) findViewById(R.id.chart); mChartView = ChartFactory.getPieChartView(this, mSeries, mRenderer); mRenderer.setClickEnabled(true); mRenderer.setSelectableBuffer(10); layout.addView(mChartView, new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT)); } else { mChartView.repaint(); } fillPieChart(); } Link of Source Code