(안드로이드 그래프,차트예제)aChartEngine, 파이그래프,막대그래프,라인그래프 예제

FSP 0 2,083 03.08 20:46

(안드로이드 그래프,차트예제)aChartEngine, 파이그래프,막대그래프,라인그래프 예제


5. Android Chart

 

5.1 aChartEngine

 

aChartEngine 라이브러리는 차트를 만들 안드로이드위한 차트 라이브러리인데 아래와 같은 챠트를 지원한다.

 

line chart

area chart

bar chart

pie chart

combined chart

 

기존 구성 요소는 다음과 같다.

 

Dataset (차트에 그려야하는 데이터 세트)

The view (원하는 차트 유형)

Renderer (뷰 그리기 방법을 제어하고 차트 모양이 바뀔 수있는 매개 변수를 설정, 렌더러에는 데이터 집합의 렌더링을 제어하는 ​​렌더러와 기본 차트의 모양을 제어하는 ​​렌더러의 두 가지 유형이 있다. (, 라벨 등))

Chart factory (데이터 세트와 렌더러를 결합하여 차트를 생성, 차트는 Activity 내부에 만들거나 팩토리가 View를 반환 할 수 있다.)

 

안드로이드 스튜디오 프로젝트를 생성하고 챠트 라이브러리를 추가해 보자.

 

1. ChartApplication 이라는 프로젝트를 생성하자. 도메인은 topcredu.co.kr 다음화면에서 EmptyActivity, 액티비티 이름은 MainActivity로 그대로 두면 된다.

 

2. http://repository-achartengine.forge.cloudbees.com/snapshot/org/achartengine/achartengine/1.2.0/

 에서 aChartEngine jar 파일을 다운로드해서 app/libs 폴더아래에 복사

3. File -> Project Structure 선택 후 Modules에서 app를 선택

5. 맨 우측 Dependencies 탭에서 오른쪽 +를 클릭 -> jar Dependency를 선택한 후 aChartEngineJAR 파일을 추가된다.

 

프로젝트 app 폴더의 build.gradle을 열어보면 DependencyaChartEngine JAR 파일이  추가되어 있는것을 확인할 수 있다.

 

compile files('libs/achartengine-1.2.0.jar')

 

 

 

 fecc9eece49d1617569a4ba9e9d6ac2e_1488973

fecc9eece49d1617569a4ba9e9d6ac2e_1488973
fecc9eece49d1617569a4ba9e9d6ac2e_1488973
fecc9eece49d1617569a4ba9e9d6ac2e_1488973 

 

 

 

 

1. ChrtApplication 프로젝트를 생성하자. MainActivity 그대로 둔다.

 

2. [activity_main.xml]

 

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
   
xmlns:app="http://schemas.android.com/apk/res-auto"
   
xmlns:tools="http://schemas.android.com/tools"
   
android:layout_width="match_parent"
   
android:layout_height="match_parent"
   
tools:context="kr.co.topcredu.chartapplication.MainActivity">

    <
LinearLayout
       
android:layout_width="368dp"
       
android:layout_height="495dp"
       
android:orientation="vertical"
       
tools:layout_editor_absoluteX="8dp"
       
tools:layout_editor_absoluteY="8dp">

        <
Button
           
android:id="@+id/btnPieChart"
           
android:layout_width="match_parent"
           
android:layout_height="wrap_content"
           
android:text="Pie Chart" />

        <
Button
           
android:id="@+id/btnLineChart"
           
android:layout_width="match_parent"
            
android:layout_height="wrap_content"
           
android:text="LINE CHART" />

        <
Button
           
android:id="@+id/btnBarChart"
           
android:layout_width="match_parent"
           
android:layout_height="wrap_content"
           
android:text="Bar Chart" />
    </
LinearLayout>
</
android.support.constraint.ConstraintLayout>

 

 

3. [MainActivity.java]

 

package kr.co.topcredu.chartapplication;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity implements View.OnClickListener {

   
public static String LOG_TAG = "MainActivity";
   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView(R.layout.
activity_main);

       
//파이 그래프
       
Button btnPieChart =  (Button)findViewById(R.id.btnPieChart);
        btnPieChart.setOnClickListener(
this);

        
//라인 그래프
       
Button btnLineChart =  (Button)findViewById(R.id.btnLineChart);
        btnLineChart.setOnClickListener(
this);

       
//막대 그래프
       
Button btnBarChart =  (Button)findViewById(R.id.btnBarChart);
        btnBarChart.setOnClickListener(
this);
    }

   
@Override
   
public void onClick(View v) {
       
switch (v.getId()) {
           
//파이그래프(PIE Chart)
           
case R.id.btnPieChart:
                Toast.makeText(MainActivity.
this, "Pie Chart", Toast.LENGTH_LONG);
                Log.i(
LOG_TAG, "PIE Chart Start...");
                startActivity(
new Intent(this, PieChartActivity.class));
               
break;
           
//라인 그래프(Line Chart)
           
case R.id.btnLineChart:
                Toast.makeText(MainActivity.
this, "Line Chart", Toast.LENGTH_LONG);
                Log.i(
LOG_TAG, "Line Chart Start...");
                startActivity(
new Intent(this, LineChartActivity.class));
               
break;
           
//막대 그래프(Bar Chart)
           
case R.id.btnBarChart:
                Toast.makeText(MainActivity.
this, "Bar Chart", Toast.LENGTH_LONG);
                Log.i(
LOG_TAG, "Bar Chart Start...");
                startActivity(
new Intent(this, BarChartActivity.class));
               
break;
        }
    }
}

 

 

4. PieChartActivity를 추가

 

[activity_pie_chart.xml]

 

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
   
xmlns:app="http://schemas.android.com/apk/res-auto"
   
xmlns:tools="http://schemas.android.com/tools"
   
android:layout_width="match_parent"
   
android:layout_height="match_parent"
   
tools:context="kr.co.topcredu.chartapplication.PieChartActivity">
    <
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_pie" android:orientation="horizontal"
           
android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1" />

    </
LinearLayout>
</
android.support.constraint.ConstraintLayout>

 

 

[PieChartActivity.java]

 

package kr.co.topcredu.chartapplication;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.LinearLayout;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.model.CategorySeries;
import org.achartengine.renderer.DefaultRenderer;
import org.achartengine.renderer.SimpleSeriesRenderer;

public class PieChartActivity extends AppCompatActivity {
   
int[] pieChartValues = {10, 10, 20, 20, 40};  //각 계열(Series)의 값

   
public static final String TYPE = "type";
   
//각 계열(Series)의 색상
   
private static int[] COLORS = new int[]{Color.YELLOW, Color.GREEN, Color.BLUE, Color.MAGENTA, Color.CYAN};

   
//각 계열의 타이틀
   
String[] mSeriesTitle = new String[] {"PIE1", "PIE2", "PIE3", "PIE4", "PIE5" };

   
private CategorySeries mSeries = new CategorySeries("계열");
   
private DefaultRenderer mRenderer = new DefaultRenderer();
   
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(
30);
        mRenderer.setLegendTextSize(
30);
        mRenderer.setMargins(
new int[]{20, 30, 15, 0});
        mRenderer.setZoomButtonsVisible(
true);
        mRenderer.setStartAngle(
90);

       
if (mChartView == null) {
            LinearLayout layout = (LinearLayout) findViewById(R.id.
chart_pie);
           
mChartView = ChartFactory.getPieChartView(this, mSeries, mRenderer);
            mRenderer.setClickEnabled(
true);
            mRenderer.setSelectableBuffer(
10);
            layout.addView(
mChartView, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
                    LinearLayout.LayoutParams.
FILL_PARENT));
        }
else {
           
mChartView.repaint();
        }
        fillPieChart();
    }

   
public void fillPieChart() {
       
for (int i = 0; i < pieChartValues.length; i++) {
           
mSeries.add(mSeriesTitle[i] + "_" + (String.valueOf(pieChartValues[i])), pieChartValues[i]);

           
//Chart에서 사용할 값, 색깔, 텍스트등을 DefaultRenderer객체에 설정
           
SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
            renderer.setColor(
COLORS[(mSeries.getItemCount() - 1) % COLORS.length]);

            mRenderer.addSeriesRenderer(renderer);

           
if (mChartView != null)
               
mChartView.repaint();
        }
    }
}

 

 

5. LineChartActivity를 추가

 

[activity_Line_chart.xml]

 

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
   
xmlns:app="http://schemas.android.com/apk/res-auto"
   
xmlns:tools="http://schemas.android.com/tools"
   
android:layout_width="match_parent"
   
android:layout_height="match_parent"
   
tools:context="kr.co.topcredu.chartapplication.LineChartActivity">
    <
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_line" android:orientation="horizontal"
           
android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1" />

    </
LinearLayout>
</
android.support.constraint.ConstraintLayout>

 

 

[LineChartActivity.java]

 

package kr.co.topcredu.chartapplication;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.LinearLayout;

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.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

public class LineChartActivity extends AppCompatActivity {

   
// 막대그래프의 가로축
   
private String[] mMonth = new String[] {
           
"Jan", "Feb" , "Mar", "Apr", "May", "Jun",
           
"Jul", "Aug" , "Sep", "Oct", "Nov", "Dec"
   
};
   
private GraphicalView mChartView;

   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView(R.layout.
activity_line_chart);
        drawChart();
    }

   
private void drawChart(){
       
int[] x = { 1,2,3,4,5,6,7,8 };
       
int[] income = { 2000,2500,2700,3000,2800,3500,3700,3800};
       
int[] expense = {2200, 2700, 2900, 2800, 2600, 3000, 3300, 3400 };

       
// Creating an  XYSeries for Income
       
XYSeries incomeSeries = new XYSeries("수입");

       
// Creating an  XYSeries for Expense
       
XYSeries expenseSeries = new XYSeries("지출");

       
// Adding data to Income and Expense Series
       
for(int i=0;i<x.length;i++){
            incomeSeries.add(x[i], income[i]);
            expenseSeries.add(x[i],expense[i]);
        }

       
// Creating a dataset to hold each series
       
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();

       
// Adding Income Series to the dataset
       
dataset.addSeries(incomeSeries);

       
// Adding Expense Series to dataset
       
dataset.addSeries(expenseSeries);

       
// Creating XYSeriesRenderer to customize incomeSeries
       
XYSeriesRenderer incomeRenderer = new XYSeriesRenderer();
        incomeRenderer.setColor(Color.
GREEN);
        incomeRenderer.setPointStyle(PointStyle.
CIRCLE);
        incomeRenderer.setFillPoints(
true);
        incomeRenderer.setLineWidth(
2);
        incomeRenderer.setDisplayChartValues(
true);

       
// Creating XYSeriesRenderer to customize expenseSeries
       
XYSeriesRenderer expenseRenderer = new XYSeriesRenderer();
        expenseRenderer.setColor(Color.
RED);
        expenseRenderer.setPointStyle(PointStyle.
CIRCLE);
        expenseRenderer.setFillPoints(
true);
        expenseRenderer.setLineWidth(
2);
        expenseRenderer.setDisplayChartValues(
true);

       
// Creating a XYMultipleSeriesRenderer to customize the whole chart
       
XYMultipleSeriesRenderer multiRenderer = new XYMultipleSeriesRenderer();
        multiRenderer.setXLabels(
0);
        multiRenderer.setChartTitle(
"수입 vs 지출 Chart");
        multiRenderer.setXTitle(
"Year 2017");
        multiRenderer.setYTitle(
"Amount in Dollars");
        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(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);

       
if (mChartView == null) {
            LinearLayout layout = (LinearLayout) findViewById(R.id.
chart_line);
           
mChartView = ChartFactory.getLineChartView(this, dataset, multiRenderer);
            multiRenderer.setClickEnabled(
true);
            multiRenderer.setSelectableBuffer(
10);
            layout.addView(
mChartView, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
                    LinearLayout.LayoutParams.
FILL_PARENT));
        }
else {
           
mChartView.repaint();
        }
    }
}

 

 

8. BarChartActivity를 추가

 

[activity_Line_chart.xml]

 

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
   
xmlns:app="http://schemas.android.com/apk/res-auto"
   
xmlns:tools="http://schemas.android.com/tools"
   
android:layout_width="match_parent"
   
android:layout_height="match_parent"
   
tools:context="kr.co.topcredu.chartapplication.BarChartActivity">
    <
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_bar" android:orientation="horizontal"
       
android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1" />
</
LinearLayout>
</
android.support.constraint.ConstraintLayout>

 

 

[BarChartActivity.java]

 

package kr.co.topcredu.chartapplication;

import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.LinearLayout;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.BarChart;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

public class BarChartActivity extends AppCompatActivity {

   
private GraphicalView mChartView;
   
private String[] mMonth = new String[]{
           
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
           
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
   
};

   
@Override
   
protected void onCreate(@Nullable Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView(R.layout.
activity_bar_chart);
        drawChart();
    }

   
private void drawChart() {
       
int[] x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
       
int[] income = {2000, 2500, 2700, 3000, 2800, 3500, 3700, 3800, 0, 0, 0, 0};
       
int[] expense = {2200, 2700, 2900, 2800, 2600, 3000, 3300, 3400, 0, 0, 0, 0};

       
// Creating an XYSeries for Income
       
XYSeries incomeSeries = new XYSeries("수입");
       
// Creating an XYSeries for Expense
       
XYSeries expenseSeries = new XYSeries("지출");
       
// Adding data to Income and Expense Series
       
for (int i = 0; i < x.length; i++) {
            incomeSeries.add(i, income[i]);
            expenseSeries.add(i, expense[i]);
        }

        
// Creating a dataset to hold each series
       
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
       
// Adding Income Series to the dataset
       
dataset.addSeries(incomeSeries);
       
// Adding Expense Series to dataset
        
dataset.addSeries(expenseSeries);

       
// Creating XYSeriesRenderer to customize incomeSeries
       
XYSeriesRenderer incomeRenderer = new XYSeriesRenderer();
        incomeRenderer.setColor(Color.
GREEN); //color of the graph set to cyan
       
incomeRenderer.setFillPoints(true);
        incomeRenderer.setLineWidth(
2);
        incomeRenderer.setDisplayChartValues(
true);
        incomeRenderer.setDisplayChartValuesDistance(
10); //setting chart value distance

        // Creating XYSeriesRenderer to customize expenseSeries
       
XYSeriesRenderer expenseRenderer = new XYSeriesRenderer();
        expenseRenderer.setColor(Color.
RED);
        expenseRenderer.setFillPoints(
true);
        expenseRenderer.setLineWidth(
2);
        expenseRenderer.setDisplayChartValues(
true);
       
// Creating a XYMultipleSeriesRenderer to customize the whole chart
       
XYMultipleSeriesRenderer multiRenderer = new XYMultipleSeriesRenderer();
        multiRenderer.setOrientation(XYMultipleSeriesRenderer.Orientation.
HORIZONTAL);
        multiRenderer.setXLabels(
0);
        multiRenderer.setChartTitle(
"수입 vs 지출 Chart");
        multiRenderer.setXTitle(
"Year 2017");
        multiRenderer.setYTitle(
"Amount in Dollars");

       
/***
         * Customizing graphs
         */
        //setting text size of the title
       
multiRenderer.setChartTitleTextSize(28);
        multiRenderer.setAxisTitleTextSize(
24);
       
//setting text size of the graph lable
       
multiRenderer.setLabelsTextSize(24);
       
//setting zoom buttons visiblity
       
multiRenderer.setZoomButtonsVisible(false);
       
//setting pan enablity which uses graph to move on both axis
       
multiRenderer.setPanEnabled(false, false);
       
//setting click false on graph
       
multiRenderer.setClickEnabled(false);
       
//setting zoom to false on both axis
       
multiRenderer.setZoomEnabled(false, false);
       
//setting lines to display on y axis
       
multiRenderer.setShowGridY(false);
       
//setting lines to display on x axis
        
multiRenderer.setShowGridX(false);
       
//setting legend to fit the screen size
       
multiRenderer.setFitLegend(true);
       
//setting displaying line on grid
       
multiRenderer.setShowGrid(false);
       
//setting zoom to false
       
multiRenderer.setZoomEnabled(false);
       
//setting external zoom functions to false
       
multiRenderer.setExternalZoomEnabled(false);
       
//setting displaying lines on graph to be formatted(like using graphics)
       
multiRenderer.setAntialiasing(true);
       
//setting to in scroll to false
       
multiRenderer.setInScroll(false);
       
//setting to set legend height of the graph
       
multiRenderer.setLegendHeight(30);
       
//setting x axis label align
       
multiRenderer.setXLabelsAlign(Paint.Align.CENTER);
       
//setting y axis label to align
       
multiRenderer.setYLabelsAlign(Paint.Align.LEFT);
       
//setting text style
       
multiRenderer.setTextTypeface("sans_serif", Typeface.NORMAL);
       
//setting no of values to display in y axis
       
multiRenderer.setYLabels(10);
       
// setting y axis max value, Since i'm using static values inside the graph so i'm setting y max value to 4000.
        // if you use dynamic values then get the max y value and set here
        
multiRenderer.setYAxisMax(4000);
       
//setting used to move the graph on xaxiz to .5 to the right
       
multiRenderer.setXAxisMin(-0.5);
       
//setting max values to be display in x axis
       
multiRenderer.setXAxisMax(11);
       
//setting bar size or space between two bars
       
multiRenderer.setBarSpacing(0.5);
       
//Setting background color of the graph to transparent
       
multiRenderer.setBackgroundColor(Color.TRANSPARENT);
       
//Setting margin color of the graph to transparent
       
multiRenderer.setMarginsColor(Color.BLUE);
        multiRenderer.setApplyBackgroundColor(
true);
       
//setting the margin size for the graph in the order top, left, bottom, right
       
multiRenderer.setMargins(new int[]{30, 30, 30, 30});
       
for (int i = 0; i < x.length; i++) {
            multiRenderer.addXTextLabel(i,
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(incomeRenderer);
        multiRenderer.addSeriesRenderer(expenseRenderer);
       
//this part is used to display graph on the xml
       
LinearLayout layout = (LinearLayout) findViewById(R.id.chart_bar);
       
//remove any views before u paint the chart
       
layout.removeAllViews();
       
//drawing bar chart
       
mChartView = ChartFactory.getBarChartView(this, dataset, multiRenderer, BarChart.Type.DEFAULT);

        layout.addView(
mChartView, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
                LinearLayout.LayoutParams.
FILL_PARENT));
    }
}

 

 

 

 

7. 생성된 AndroidManifest.xml 파일의 모양은 다음과 같다.

 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   
package="kr.co.topcredu.chartapplication">

    <
application
       
android:allowBackup="true"
       
android:icon="@mipmap/ic_launcher"
       
android:label="@string/app_name"
       
android:roundIcon="@mipmap/ic_launcher_round"
       
android:supportsRtl="true"
       
android:theme="@style/AppTheme">
        <
activity android:name=".MainActivity">
            <
intent-filter>
                <
action android:name="android.intent.action.MAIN" />

                <
category android:name="android.intent.category.LAUNCHER" />
            </
intent-filter>
        </
activity>
        <
activity android:name=".PieChartActivity" />
        <
activity android:name=".LineChartActivity" />
        <
activity android:name=".BarChartActivity"></activity>
    </
application>

</
manifest>

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Comments