안드로이드 기반 앱 개발부
안드로이드 pie차트, bar차트, line차트
안녕하십니까~~
커피백작입니다.
오늘은 차트를 생성하는 예제를 가져왔습니다.
이것저것 차트 예제들이 잘 나온것도 많이 있는데, 오늘 굳이 다른 곳에서 예제를 가져온건 파일도 하나 같이 첨부해서 쓰려구용
먼저 소스를 구한 링크입니다!
http://ojc.asia/bbs/board.php?bo_table=LecAndroid&wr_id=94
위의 링크에서 보시면 아래의 파일을 다운로드하라고 나옵니다.
해당 페이지에서 다운로드하라고 보내주는 링크는 404 뜨더라구욤.. ㅋㅋ;
그래서 직접 구해서 이곳에 올립니다!
위의 파일을 다운로드 해주시고, 아래와 같이 추가를 해주시면 됩니다.
좌측 부터 화살표 따라 우측 3번째로 가시면 되용.
project - app - libs 폴더안에 다운받으신 파일을 추가해주시구요
File - Project Structure - app - Dependencies 에서 + 버튼 누르시고 jar dependency 누르시면 나오는 창에서 아까 libs 에 넣은 파일을 찾아 ok 버튼 눌러주면,
Project Structure 창의 Dependencies 에서 빨간 줄 처럼 추가 된게 보이실 겁니다.
ok 버튼 누르고 나오셔서 아래 사진 처럼 들어가봅시다.
dependencies 에 빨간줄 같이 추가가 되었군요!
예제를 퍼온 링크에선 compile 로 써있지만 제건 implementation 이네요.
여차저차 위의 차례를 다 하셨다면, 준비는 끝난 셈이라 봅니다.
이제는 소스코드들을 손보면 되겠어요
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;
}
}
}
PieChartActivity
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, 100}; //각 계열(Series)의 값
public static final String TYPE = "type";
//각 계열(Series)의 색상
private static int[] COLORS = new int[]{Color.YELLOW, Color.GREEN, Color.GRAY, Color.MAGENTA, Color.CYAN, Color.BLUE};
//각 계열의 타이틀
String[] mSeriesTitle = new String[] {"PIE1", "PIE2", "PIE3", "PIE4", "PIE5", "tester" };
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();
}
}
}
BarChartActivity
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};
int[] tester = {1000,1200,1600,3000,500,5000,5000,5000,0,0,0,0};
// Creating an XYSeries for Income
XYSeries incomeSeries = new XYSeries("수입");
// Creating an XYSeries for Expense
XYSeries expenseSeries = new XYSeries("지출");
XYSeries testers = 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]);
testers.add(i, tester[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);
dataset.addSeries(testers);
// 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);
XYSeriesRenderer testerRenderer = new XYSeriesRenderer();
testerRenderer.setColor(Color.BLUE);
testerRenderer.setFillPoints(true);
testerRenderer.setLineWidth(2);
testerRenderer.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);
multiRenderer.addSeriesRenderer(testerRenderer);
//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));
}
}
LineChartActivity.java
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 };
int[] tester={1000,1200,1600,3000,500,5000,5000,5000};
// Creating an XYSeries for Income
XYSeries incomeSeries = new XYSeries("수입");
// Creating an XYSeries for Expense
XYSeries expenseSeries = new XYSeries("지출");
XYSeries testers=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]);
testers.add(x[i], tester[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);
dataset.addSeries(testers);
// 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);
XYSeriesRenderer testerRenderer = new XYSeriesRenderer();
testerRenderer.setColor(Color.BLUE);
testerRenderer.setPointStyle(PointStyle.CIRCLE);
testerRenderer.setFillPoints(true);
testerRenderer.setLineWidth(2);
testerRenderer.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);
multiRenderer.addSeriesRenderer(testerRenderer);
// 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();
}
}
}
네 액티비티 부분은 끝났구요.
형광 부분이 원본소스에서 제가 추가한 부분입니다.
해당 부분들을 넣어줌으로써 원하는 항목이 추가되어 chart 가 만들어 진거죠.
소스를 주욱 보시고 실행화면 보시다 보면 이해되서 막 활용하실수 있으리라 봅니당
MainActivity.java 는 그냥 버튼으로 차트액티비티들 불러오는게 전부에요.
xml 파일들 들어가겠습니다.
아, 그전에 에러 하나에 대해 말씀 드릴게요.
xml 파일명에는 대문자 안되요!
만약 파일명에 대문자 쓰시면 빌드 중에 다음과 같은 에러가 납니다.
layout\activity_Line_chart.xml: Error: 'L' is not a valid file-based resource name character: File-based resource names must contain only lowercase a-z, 0-9, or underscore
xml 로 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=".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>
<?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=".PieChartActivity">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<LinearLayout
android:id="@+id/chart_pie"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal" />
</LinearLayout>
</android.support.constraint.ConstraintLayout>
<?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=".BarChartActivity">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<LinearLayout
android:id="@+id/chart_bar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal" />
</LinearLayout>
</android.support.constraint.ConstraintLayout>
<?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=".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>
이로써 xml 파일들도 끝났습니다.
마지막으로 androidmanifests 를 손보겠습니다.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="circlechart3">
<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"/>
</application>
</manifest>
메니페스트에는 activity.java 파일들의 이름들만 해당 위치에 추가해주세요
네~~ 이로써 다 끝났어요.
네 초기설정도, 소스도 끝난겁니다.
이제 실행화면을 올릴게요.
짜장~~~
네? 짜장면 안시켰어요. 등장 효과음입니다. ㅋㅋㅋㅋㅋㅋㅋ
흠흠, 여튼 보시는 바와 같이 퍼~런 차트값들은 새로 추가한 녀석들입니다.
네, 이렇게 차트가 3개 만들어진다는 것을 확인 했으니, 제가 다음에 또 써먹어야지요.
캬캬캬 더운데 건강 관리잘하시구요들~ 담에 봐요~~
'안드로이드 기반 앱 개발부' 카테고리의 다른 글
안드로이드 원형 차트 만들기 (0) | 2018.08.08 |
---|---|
안드로이드. Colors.xml 과 R 에러. (0) | 2018.08.08 |
안드로이드 권한 취득 소스 (0) | 2018.08.07 |
주소록 데이터 가져오기 (0) | 2018.08.07 |
'안드로이드 기반 앱 개발부'의 다른글
- 현재글안드로이드 pie차트, bar차트, line차트