'angualr2 chart'에 해당하는 글 3건


이전 포스팅에 이어서 하겠습니다


개인프로젝트로 만든 크롤러앱에서 수집한 데이터를 가지고 차트로 표현해보려고합니다.


기준프로젝트 화면  : http://moonna.tistory.com/3




신규등록 을 마치면 위와 같이 목록들이 보인다 


수집한해시태그 맥북 로우 클릭후 데이터를 가져와 차트로 보여줄까합니다




collect.component.html

1
2
3
4
    <ag-grid-ng2 #agGrid style="width: 100%; height: 200px;" class="ag-fresh"
                 [gridOptions]="gridOptions" (rowClicked)='onRowClicked($event)'
                 >   
    </ag-grid-ng2>
cs


그리드 로우 클릭이벤트를 생성해줍시다 



collect.component.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
onRowClicked(event: any) { 
 
      this.searchdata = event.data;
      
       var query = {
                        "name" : this.searchdata.name,
                        "searchquery" : this.searchdata.hashtag
       }
       
        var headers = new Headers(); 
        headers.append('Content-Type''application/json')
        this.http.post('http://localhost:4100/searchid',query,{headers: headers}).subscribe((res) => {
        this.resultData = res.json();
         
}
cs


로우클릭시 event값을 가져와 변수에집어넣어줍니다 


그후 JSON 형태로 만들어준후 POST 시켜줘서 해당조건과 맞는 데이터를 가져옵니다  


그후 가져온 데이터를 this.resultData 변수에 넣어줍니다 




1
2
3
4
5
6
7
8
9
 var TempResultData = new Array()  //수집된데이타 날짜    배열
 
        for(var i = ; i < this.resultData.length - 1; i ++)
        {
            TempResultData[i] = this.resultData[i]['date'].substring(0,10)
        }
 
         TempResultData.sort(this.sortDate)
 
cs


그후 수집된 데이타 날짜를 가져오는 배열을 하나 선언합니다


중간에 .substring(0,10) 을 해준이유는 저장된 날짜형식이  아래 그림과같이 시분초 까지 저장되어있습니다 




날짜별로 소트를 시킨후  로그를 살펴보면 



엄청많은 데이터가 보이는것을 확인할수가있습니다 


차트의 하단부에 월,일부분만 필요해서 월 일 부분만 따로 추렸습니다  이많은 데이터에서 중복된 데이터를 제거를 한후 


카운트까지해볼 생각입니다 


1
2
3
4
5
6
7
        //array 중복 제거 
        var uniq = TempResultData.reduce(function(a,b){
            if (a.indexOf(b) < ) a.push(b);
            return a;
        },[]);
 
        this.barChartLabels = uniq
cs

indexof() 를 이용해서 중복값을 처리해주고 필요한  일자를 아래그림과 같이 추렸습니다 



중복된 날짜는 따로 구했으니 중복된값을 카운트 해보도록하겠습니다 


1
2
3
4
5
        for(var value in TempResultData) {
 
        var index = TempResultData[value]
        overlapData[index] = overlapData[index] == undefined ? : overlapData[index] += 1
        }   
cs



중복된 날짜를 비교해서 카운팅을 해줍니다


그후에 나온값들을 차트 데이터셋에 입력시켜주면 끝!


1
this.barChartData = [{data : overlapcount,label:this.resultData[0]['searchquery']}]
cs


실행화면 





WRITTEN BY
내가달이다

,

셋팅이 완료 되었다 가정하고 진행합니다


여러개의 차트가 있는데 그중에 가장 많이 쓰이는 bar형식의 차트를 이용해버려합니다 


testsample1.html

1
2
3
4
5
6
7
8
9
10
11
12
13
<div>
  <div style="display: block">
    <canvas baseChart
            [datasets]="barChartData"
            [labels]="barChartLabels"
            [options]="barChartOptions"
            [legend]="barChartLegend"
            [chartType]="barChartType"
            (chartHover)="chartHovered($event)"
            (chartClick)="chartClicked($event)"></canvas>
  </div>
  <button (click)="randomize()">Update</button>
</div>
cs


testsample1.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
   public barChartOptions:any = {
    scaleShowVerticalLines: false,
    responsive: true
  };
  //하단 라벨
  public barChartLabels:string[] = ['2006''2007''2008''2009''2010''2011''2012'];
  //바 타입
  public barChartType:string = 'bar';
  public barChartLegend:boolean = true;
 
  public barChartData:any[] = [
    {data: [65598081565540], label: 'Series A'},
    {data: [28484019862790], label: 'Series B'}
  ];
 
  // events
  public chartClicked(e:any):void {
    console.log(e);
  }
 
  public chartHovered(e:any):void {
    console.log(e);
  }
 
cs


오픈소스에 제공하는 간단한 데모를 적용시켜본것입니다


datasets , labels,options 등을 ts 에서 값들을 입력해줍니다 


실행해보겠습니다




다음 포스팅에는 크롤링한데이터를 적용해볼예정입니다 



WRITTEN BY
내가달이다

,

최근 크롤러웹페이지를 만든후 크롤링한데이터를 웹상에 차트상으로 표현을 해주고싶어서 


무료이면서 가벼운 모듈을 찾다가 


ng2-charts 가 괜찮아보여서 사용하려합니다  http://valor-software.com/ng2-charts/ 


github 오픈소스 공개되어있으니 데모를 보고 알맞게 적용하시면될거같습니다 



1. ng2-chart 를  npm을 이용해 설치합니다  


1
npm install ng2-charts --save
cs

2. chart.js 가 필요하니 이것도 설치해줍시다  이부분이 셋팅이 잘안되있을시 

1
npm install chart.js --save
cs



다음과 같이 오류가발생할수 있는데 이같은경우는 경로를 제대로 잡아주면 해결됩니다 .



이런식으로 나오면 설치완료!


3. 중요한부분인데 chart.js 을 포함시켜줘야됩니다 


index.html

1
<script src="node_modules/chart.js/src/chart.js"></script>
cs




설치 끝!


ps. 혹여나 저처럼 system.js 사용하시는분을 위해 추가로 남겨요


이것때문에 삽질좀했습니다 ..



systemjs.config.js


map 구문 안에 추가

1
"ng2-charts""node_modules/ng2-charts",
cs



package 구문 안에 추가 


1
 "ng2-charts": { main: 'ng2-charts.js' }
cs


여기까지 하셨으면 셋팅은 끝나신겁니다


다음 포스팅에 간단하게 적용된 데모를 포스팅할예정입니다 


WRITTEN BY
내가달이다

,