블로그 이미지
윤영식
Full Stacker, Application Architecter, KnowHow Dispenser and Bike Rider

Publication

Category

Recent Post

2018. 10. 17. 15:11 Data Visualization/Vega

Vega는 선언적인 차트 생성 라이브러리이다. 좀 더 추상화하고 쉽게 사용할 수 있도록 Vega-lite를 제공한다. C3.js 또는 네이버의 C3.js 확장판인 Billboard.js를 생각하면 된다.




특징


- SVG, Canvas를 지원한다. 

- Javascript코드없이 JSON환경으로 차트를 생성한다. 

- Editor, Recommendation Charting해주는 Voyager등을 제공한다.


테스트: https://vega.github.io/editor/#/ 접속해서 다음 환경값을 넣는다. 


{
"$schema": "https://vega.github.io/schema/vega-lite/v2.json",
"data": {"url": "data/seattle-weather.csv", "format": {"type": "csv"}},
"mark": "bar",
"encoding": {
"x": {"timeUnit": "month", "field": "date", "type": "ordinal"},
"y": {"aggregate": "mean", "field": "precipitation", "type": "quantitative"}
},
"config": {"axisY": {"minExtent": 30}}
}





개념 


Vega-lite 소개 동영상을 보고 전반적으로 이해하자. 


좀 더 자세한 개념설명





사용예


Elastic Search에서는 Customizing Chart를 만들기 위해 Vega를 기능으로 추가하여 사용할 수도 있다.


Elastic Search에서 Vega 구현 예제 소스

Vega, Vega-lite, 또는 Vega Editor, Vega Voyager등은 Standalone library 형태로 애플리케이션에 포함하여 사용할 수 있다.




posted by 윤영식
2015. 8. 20. 18:05 Data Visualization/D3.js

올 하반기는 D3.js를 이용한 차트 라이브러리 만들기를 주된 작업으로 잡고 있다. 데이터 시각화를 위해 SVG를 자유자재로 다루기 위해 D3.js를 심도있게 이해하는 것이 어느 때보다 필요하기 때문이다. AngularJS/React/Meteor 는 데이터 시각화 서비스를 개발하기 위한 기술로 익히고 있다. 마이크 보스톡의 튜토리얼 레퍼런스에 나온 내용중 좋은 기사를 실습 요약한다. 





준비하기 

  

테스트를 위해 로컬에서 하지 않고 JSBin 서비스를 이용한다. GitHub 계정으로 로그인을 하고 자신이 원하는 테마(Theme)를 아래와 같이 설정할 수 있다. Monokai와 Sublime 키바인딩, FontSize 11로 설정을 했다. "Add library"에서 "D3 3.x" 를 선택하면 HTML에 자동으로 추가된다. 





엘러먼트 선택


D3는 jQuery의 Selector 처럼 Selection(셀렉션)을 통해 문서를 접근할 수 있다. 그리고 선택된 셀랙션에 대해 메소드 체이닝(Chaining Methods)를 통해 제어를 할 수 있다. 체이닝의 이점은 var 를 사용하지 않아도 되고 코드를 간결하게 유지할 수 있다. 

Let's Make Bar Chart on jsbin.com





차트 만들기 


HTML로 직접 바차트를 만들 수 있지만 D3를 이용해 어떻게 만드는지 보자. 

JS Bin on jsbin.com


코드의 순서는 다음과 같다. 

- var chart  = d3.select('.chart') : selector를 이용해서 Chart container를 선택한다. 

- var bar = chart.selectAll('div') : 데이터 조인 (data join)을 위해 셀랙션(selection)을 초기화 한다. 데이터 조인은 데이터 변경에 따라 엘러먼트를 생성, 업데이트, 삭제할 수 있는 것이다. (자세한 사항은 "Thinking with joins"를 참조한다)

- var barUpdate = bar.data(data) : selection.data를 통해 데이터를 셀랙션과 조인(join)한다. 

- var barEnter = barUpdate.enter().append('div') : 'div' 태그가 .chart 안에 존재하지 않기 때문에 barUpdate는 일어나지 않는다. 없을 경우 새로운 데이터에 대한 임의위치(placeholder)를 만들어 주기 위해 enter()를 호출한 후, 임의위치에 append('div')를 통해 div 태그를 신규 생성한다. 

- barEnter.style('width', ....) : 신규 생성된 div에 대한 스타일을 설정한다. D3에서는 attr(), style(), property()를 통해 엘러먼트를 설정할 수 있다. 

- barEnter.text(...) : 레이블을 설정한다. 





스케일 맞추기 


위의 소스를 보면 width에 대해 10 상수값이 쓰였다. 실제값을 정의역값이라하고 domain(도메인)이라하며, 10을 곱하여 나온 변경된 값을 치역(range)값이라 한다. 수치에 대한 일정한 스케일(Scale)을 만들어 주는 기능이 D3에서는 linear scale 이다. x에 대한 스케일을 만들어 보자.

JS Bin on jsbin.com





SVG를 사용해 만들기 


위에 소스는 HTML을 통해 만들었지만 SVG(Scalable Vector Graphics)를 이용해 표현해 보도록 한다. SVG를 사용하면 네이티브 레벨에서 다양한 모양을 만들어 낼 수 있다. HTML에 <!DOCTYPE html> 태그를 최상단에 넣어주고 사용할 수 있다. SVG는 HTML의 일반 스타일이 아닌 다른 스타일 명을 쓴다. 예로 background-color는 fill로 쓴다. SVG 프로퍼티 스펙을 참조한다. 좌표는 top-left 코너에서 시작한다. SVG로만 차트를 표현한 예이다. 

JS Bin on jsbin.com


- transform을 이용해 크기의 절대좌표값으로 translate(x, y)를 통해 이동을 하고 있다. 

- g 그룹 논리 태그를 통해 하위에 SVG rect으로 사각형을 표현한다. 

- text 태그를 통해 레이블을 설정한다. 


D3를 이용해 다시 표현해 보자. g 셀랙션은 data 배열 6개 만큼이 생성되어 rect과 text 태그를 통해 바차트를 그린다. 

JS Bin on jsbin.com


- x 스케일을 만든다 

- svg 의 크기를 결정한다 

- svg안에 g가 들어가므로 enter selection을 통해 추가하고 transform으로 g 위치를 옮긴다. 

- var bar 값은 data 값 수 만큼의 g 배열을 리턴 받아 rect과 text를 설정한다. rect과 text는 g로 부터 data 값을 받아 사용한다. 





데이터를 불러와서 차트그리기


D3는 TSV(Tab-seperated values)나 CSV(Comma-seperated values)로 파일 형식을 읽어와서 JSON으로 변환해 사용할 수 있다. d3.csv API를 참조한다. 테스트를 위해서 GitHub에 별도 저장소를 하나 만들고 data.tsv 파일을 하나 만든다. (탭으로 구분)

name value

Locke 4

Reyes 8

Ford 15

Jarrah 16

Shephard 23

Kwon 42


GitHub에 파일을 만들고 파일을 선택하고 "Raw" 버튼을 클릭하면 상단에 접근 주소가 나온다. 

예) https://raw.githubusercontent.com/mobiconsoft/d3_practice/master/data.tsv

사용할 Raw Data 주소이다. 


JSBin에서 TSV 파일을 호출해 보자. 

JS Bin on jsbin.com


- 데이터의 갯수를 모르기 때문에 호출후 x.domain 정의역 값을 설정한다. 

- 데이터는 [{name: 'Locke', value: 4}, ....] 와 같이 데이터가 오브젝트이므로 function(d) { return d.value; } 값을 사용한다. 

- tsv 호출시 값에 대한 컨버젼을 하지 않고 전부 string으로 취급하므로 type 펑션은 숫자로 변환하는 유틸이다. 





컬럼 차트로 전환하기 


수평 바차트를 수직 컬럼 차트로 변환해 보자. X축은 이름을 표현하고 Y축은 값을 표현할 것이다. X축과 같이 문자 알파벳으로 표현될 경우는 Ordinal 스케일을 사용해야 하고 치역의 값을 수량적으로 할 수 없기 때문에 자동으로 맞춰주는 rangeBands 또는 rangePoints 를 사용한다. rangeBands/Points는 각 시리즈의 넓이를 의미하고 시르즈(바)간의 padding을 지정해 주고 싶다면 rangeRoundBands를 통해 파라미터를 설정할 수 있다. 

JS Bin on jsbin.com


- X축은 이름이기 때문에 Ordinal 스케일이다. 

- bar의 X 스케일 만큼 이동하고, rect의 y점을 지정 후 그린다.

- x.rangeBand()는 바의 넓이를 자동으로 계산해 넘겨준다. 





축 추가하기 


컬럼 차트만 그려지니 썰렁하다. 축을 그려보자. D3는 축을 만들 수 있도록 d3.svg.axis() API를 제공하고, 축의 방향을 설정한 후 기존에 생성한 x, y Scale을 설정한다. 축에 스케일 설정을 하고 SVG의 g 그룹에 축을 설정할 때는 selection.call API를 사용한다. 축을 설정하면 <g class="y axis"> 또는 <g class="x axis"> 클래스가 자동 설정된다. 해당 값은 사용자가 아래와 같이 수정할 수 있다. 

<style>

.bar {

  fill: steelblue;

}


.axis text {

  font: 10px sans-serif;

}


.axis path,

.axis line {

  fill: none;

  stroke: #000;

  shape-rendering: crispEdges;

}


.x.axis path {

  display: none;

}

</style>


JSBin 코드를 보자.

JS Bin on jsbin.com


- SVG 넓이 안에 들어가는 차트를 위한 마진을 설정한다. 

- x, y 스케일을 구한다. 

- x, y 축을 스케일을 적용해 구한다. 

- 차트 영역을 설정하고 차트 셀랙션을 생성한다 

- 데이터가 들어오면 x, y 스케일에 대한 정의역(domain)값을 설정한다. 

- x, y 스케일에 대한 정의역 값이 설정된 후에야 차트 g 그룹에 x, y Axis를 설정할 수 있다. 정의역값이 설정되기 전에 축 설정이 되면 축의 Tick 값이 표현되지 않는다. 

- .bar 클래스를 선택하고 데이터를 조인하면 임의영역(placeholder)가 생성되고, 여기에 rect을 append하여 컬럼을 기존처럼 그린다.  




<참조>


- 원문 : Let's Make a Bar Chart  (보스톡의 소스)   

- SVG 스펙


posted by 윤영식
2013. 8. 6. 19:34 Data Visualization/D3.js

D3.js 는 데이터 시각화 프레임워크로 잘 알려져 있고, 자바스크립트로 개발을 한다. HTML5의 SVG(Scalable Vector Graphic) 을 통하여 다양한 화면 해상도에서도 깨짐없는 Visualizing이 가능하다. D3.js를 익히기 위한 과정을 정리해 본다. 





개념 익히기 


   - 일반적인 사항에 대하여 알자

    + D3 는 웹표준기술을 이용해 데이터를 비쥬얼라이징할 수 있는 라이브러리다. 

    + D3.js 창시자인 엠보스톡의 워크샵을 통해 개념을 잡자

    + mbostock의 작업내역 감상하기


  - 기본적인 접근 방법에 대한 생각

  - 중요한 6가지 개념에 대해서 설명한다

    + Selectors : 기초이해Selection의 동작원리

    + Data & Joins(Enter, Update, Exit) : Thinking with Joins, Update/Enter/Exit에 대한 이해, 코드로 이해하기, 다시 기본부터 이해하기

    + Scales

    + Axis

    + Shapes

    + Layouts 

    




초급 학습하기 


  - http://www.dashingd3js.com/ 

    + 직접 실습한 내용 [1], [2], [3], [4]

    + D3.js 의 중요성 -> D3.js 안에 구현된 SVG API사용 -> Scale -> Axis 만들기

  - http://misoproject.com/d3-chart/tutorials/quickstart 

    + 순서대로 차트 만들어 나가기 

  - http://christopheviau.com/d3_tutorial/

    + Try D3 now -> 페이지 위쪽에 있는 도형모양을 클릭해 보라

    + 따라하며 기초개념 잡기   

  - http://www.youtube.com/user/d3Vienno 

    + 동영상 강좌를 따라한다

    + dashingd3js.com 과 유사한 과정이지만 좀 더 재미난 것들을 다룬다

    + 따라서 dashingd3js.com 을 다 본후 따라해 본다 




중급 학습하기 


  - D3.js 한글화 문서

    + 한글화 API

  - http://www.recursion.org/d3-for-mere-mortals/

    + d3 차트 만드는 기술 & 디버깅  

  - http://www.d3noob.org/

    + d3 차트 만들기 Tip & Tricks

  - D3로 구현된 다양한 Chart와 Visualization 사이트

  - Dimensional Charting Framework

    + Chart간의 interactive 표현에 능함

 


  - http://nvd3.org/ 에서 D3.js 를 가지고 만들어진 차트를 살펴보자

    + 실시간 코딩으로 차트 만들어 보기





고급 학습하기 


  - D3 Tip & Tricks 실습하기 : 구글링하면 PDF자료 얻을 수 있다 (d3 tips and tricks pdf)

  - D3.js 위키의 튜토리얼을 참조하자.

  - D3.js를 이용해 자신만의 차트 컴포넌트를 만든다면 다음의 가이드를 따른다. 

    + Resuability Chart를 만들기 개념 :  Repeatable, Modifiable, Configurable, Extensible 

    + 오픈소스 차트를 연구하자 : xCharts, C3.js


  - Functional Reactive Programming(FRP)와 D3.js의 관계도 살펴보면 어떨까?

    + Bacon.js와 D3.js 사용예


  - 어차피 서버에서 데이터를 받아서 화면 처리를 해야 하므로 웹앱프레임워크와 연동해 보자

    + AngularJS & D3.js 연동 예, 다른 연동 예 

    + D3.js를 Angular Directive로 만들어 놓는 OSS

  - Socket.IO를 통하여 System Realtime Monitoring 하기  (샘플소스)

  - Node.js + Express + Socket.io + D3.js 구성하기  (소스)


 ** 중급, 고급은 포스팅이나 소스를 통하여 스스로 익히는게 답!




<참조>

  - D3 강좌

  - Stanford 대학교 Visualization Group

    + Visualization에 대한 논문을 볼 수 있다. 내가 해보고 싶은 연구분야

posted by 윤영식
2013. 8. 6. 19:19 Data Visualization/D3.js

D3.js 의 Text 출력 방법 및 Axis 컴포넌트에 대해 실습해 본다 



1. SVG Text Element

  - 글자는 font, position, writing direction, attribute(rendering)을 정해야 함 

  - 정의 (참조)

<text x="20" y="20" font-family="sans-serif" font-size="20px" fill="red">Hello!</text>

  - 차트에 Text Label을 붙여보자 

<!DOCTYPE html>

<html>

  <head>

  <script type="text/javascript" src="d3.min.js"></script>

  </head>

  <body>

  <svg width="200" height="200">

 <g>

   <circle cx="20" cy="20" r="20" fill="red" />

   <circle cx="70" cy="70" r="20" fill="purple" />

 </g> 

 <text x="20" y="20" font-family="sans-serif" font-size="20px" fill="green">YoungSik!</text>

</svg>

  </body>

</html>

 글자가 나옴 


  - 다르게 표현 

//Circle Data Set

var circleData = [

  { "cx": 20, "cy": 20, "radius": 20, "color" : "green" }, 

  { "cx": 70, "cy": 70, "radius": 20, "color" : "purple" }];


//Create the SVG Viewport

var svgContainer = d3.select("body").append("svg")

                                     .attr("width",200)

                                     .attr("height",200);


//Add circles to the svgContainer : virutal element 만들기 

var circles = svgContainer.selectAll("circle")

                           .data(circleData)

                           .enter()

                           .append("circle");


//Add the circle attributes : data binding to element

var circleAttributes = circles

                       .attr("cx", function (d) { return d.cx; })

                       .attr("cy", function (d) { return d.cy; })

                       .attr("r", function (d) { return d.radius; })

                       .style("fill", function (d) { return d.color; });


//Add the SVG Text Element to the svgContainer : virtual element 만들기 

var text = svgContainer.selectAll("text")

                        .data(circleData)

                        .enter()

                        .append("text");


//Add SVG Text Element Attributes 텍스트 : data binding to element

var textLabels = text

                 .attr("x", function(d) { return d.cx; })

                 .attr("y", function(d) { return d.cy; })

                 .text( function (d) { return "( " + d.cx + ", " + d.cy +" )"; })

                 .attr("font-family", "sans-serif")

                 .attr("font-size", "20px")

                 .attr("fill", "red"); 

  좌표값이 찍혀 나온다 



2. D3.js Axis Component

  - Axis component는 horizontal-axis 와 vertical-axis를 쉽게 추가하도록 하는 것임 

  - x-axis, y-axis

  - 축 생성

var xAxis = d3.svg.axis();

  - axis는 scale과 관련이 있다 : xAxis는 function 값이 출력된다 

var axisScale = d3.scale.linear()

                 .domain([0,100])

                 .range([0,100]);


var xAxis = d3.svg.axis()

                  .scale(axisScale);


typeof(xAxis);

// function

  - axis가 function이므로 call 하는 것이다 

//Create the SVG Viewport

var svgContainer = d3.select("body").append("svg")

                                     .attr("width", 400)

                                     .attr("height", 100);


//Create the Scale we will use for the Axis

var axisScale = d3.scale.linear()

                         .domain([0, 100])

                         .range([0, 400]);


//Create the Axis

var xAxis = d3.svg.axis()

                   .scale(axisScale);


//Create an SVG group Element for the Axis elements and call the xAxis function

var xAxisGroup = svgContainer.append("g")

                              .call(xAxis);

  group tag와 그안으로 line과 text element가 포함되었다 (참조)

  + axis element는 group 안에서 생성된다 

  + 주어진 scale과 range를 기준으로 오른쪽으로 tick mark 스페이스가 생긴다 

  + 각 SVG element의 Axis Function은 SVG Transformation을 갖는다

  + 각 SVG element의 Axis Function은 line 과 text로 구성된다 

  + 마지막은 SVG Path가 SVG Viewport를 넘어가서 글자가 린다 


* 좀 더 심화학습을 하고 싶다면? 참조

posted by 윤영식
2013. 8. 5. 18:51 Data Visualization/D3.js

실습-1 에서 데이터를 어떻게 사용하는지까지 살펴보았다. 이번에는 데이터와 DOM을 바인딩하여 다양한 모양을 그려본다 



1. 준비

  - p tag 없는 html에서 시작

<!DOCTYPE html>

<html>

  <head>

  <script type="text/javascript" src="d3.min.js"></script>

  </head>

  <body>

  </body>

</html>

  - p tag의 __data__ 속성값 확인

var theData = [1,2,3];

var p = d3.select('body').selectAll('p').data(theData).enter().append('p').text(function(d) { return d;});

console.log(p);

  - 결과 : p element 객체가 array 형태로 return 된다 



2. SVG Shape Element 그리기

  - circle svg shape 그려보기 (참조)

  - circle 필수 attribute

    + cx : 원중심의 x좌표값

    + cy : 원중심의 y좌표값

    + r : 원 반지름

  - 모양 만드는 순서 

    + SVG의 크기 width, height를 정한다 : append('svg')

var circleRadii = [40, 20, 10];

var svgContainer = d3.select("body").append("svg").attr("width", 200).attr("height", 200);

    + SVG 안에 child element로 포함될 SVG shape element를 append(추가)한다

var circles = svgContainer.selectAll('circle'). data(circleRadii).enter().append('circle');

    circles 객체의 내역

   


    + 데이터를 DOM과 바인딩하여 원을 그린다

var circleAttributes = circles.attr('cx', 50).attr('cy', 50).attr('r', function(d){ return d; }).style('fill', 'blue');

      결과로 파란원만 나온다 

 

  - 값에 따라서 원의 색깔을 틀리게 해보자 

var circleAttributes = circles.attr('cx', 50).attr('cy', 50).attr('r', function(d){ return d; }).style('fill', function(d) {

  if(d == 40) { return 'green'; }

  else if(d == 20) { return 'yellow'; }

  else if(d == 10) { return 'orange'; }

  else { return 'blue';}

});

  - 결과 



3. SVG 좌표 기준 알기 

  - SVG는 일반적은 x-y축에 대한 기준을 사용하지 않는다 (참조)

  - SVG x=0, y=0 은 top left 에서 시작한다 

    x 값은 left -> right

    y 값은 top -> bottom 

    으로 증가한다 


  - 좌표 테스트

// 데이터

var spaceCircles = [30, 70, 110];

// svg 영역 확보

var svgContainer = d3.select("body").append("svg")

.attr("width", 200)

.attr("height", 200);

// svg shape virutal element 생성

var circles = svgContainer.selectAll("circle")

.data(spaceCircles)

.enter()

.append('circle');

// 데이터 바인딩통하여 원그리기 

var circleAttributes = circles

.attr("cx", function (d) { return d; })

.attr("cy", function (d) { return d; })

.attr("r", 20 );

 * 원의 색깔도 넣어보자 ^^



4. D3.js 의 자료구조 

  - 계속 Array를 사용해 왔다 : 배열의 값은 number, string, object, array, HTML Element, DOM element 가능 (참조

  - Array로 넘어 올때 index에 대한 접근도 가능하다 : i 값이 array의 index 값 

var theData = [ 1, 2, 3 ];

var p = d3.select("body").selectAll("p")

  .data(theData)

  .enter()

  .append("p")

  .text(function (d, i)

    return "i = " + i + " d = "+d; 

   });

  - 외부에서 데이터를 가져올 수도 있는데 이때는 반드시 배열로 와야한다 

> XMLHttpRequest

> text file

> JSON blob

> HTML document fragment

> XML document fragment

> comma-separated values (CSV) file

> tab-separated values (TSV) file

  - JSON 형태의 데이터는 반드시 key: value 모두 double quotes로 묶는다. 그리고 d3에 데이터전달시 JSON Array 이어야 함 

var seniorEngineer = {

 "name":"YoungSik",

 "drink":"not much",

 "number":"9578"

};

  - JSON Array로 활용하여 원을 표현해 보자(참조)

// 데이터 

var jsonCircles = [

  { 

   "x_axis": 30,

   "y_axis": 30,

   "radius": 20,

   "color" : "green"

  }, {

   "x_axis": 70,

   "y_axis": 70,

   "radius": 20,

   "color" : "purple"

  }, {

   "x_axis": 110,

   "y_axis": 100,

   "radius": 20,

   "color" : "red"

}];

// SVG 컨테이너 영역 확보 

var svgContainer = d3.select("body").append("svg")

                                    .attr("width", 200)

                                    .attr("height", 200);

// SVG Shape virtual element 생성 

var circles = svgContainer.selectAll("circle")

                          .data(jsonCircles)

                          .enter()

                          .append("circle");

  - console.log(circles); 를 수행하면 __data__ 속성이 JSON 객체로 할당된 것을 볼 수 있다


  - 3단계인 데이터를 DOM에 바인딩 해보자 

var circleAttributes = circles

  .attr('cx', function(d) { return d.x_axis; })

  .attr('cy', function(d) { return d.y_axis; })

  .attr('r', function(d) { return d.radius; })

  .style('fill', function(d) { return d.color; });



5. SVG 기본 모양 알아보기 

  - SVG Basic Shape에 대해서 알아본다 (참조)

  - Circle : cx, cy, r

  - Rectangle : x, y, width, height

// SVG 컨케이너 영역 확보

var svgContainer = d3.select("body").append("svg")

                                    .attr("width", 200)

                                    .attr("height", 200);


// SVG Shape 그리기

var rectangle = svgContainer.append("rect")

                            .attr("x", 10)

                            .attr("y", 10)

                            .attr("width", 50)

                            .attr("height", 100);


  - Ellipse : cx, cy, rx, ry

var svgContainer = d3.select("body").append("svg")

                                    .attr("width", 200)

                                    .attr("height", 200);


//Draw the Rectangle

var ellipse = svgContainer.append("ellipse")

                            .attr("cx", 100)

                            .attr("cy", 100)

                            .attr("rx", 50)

                            .attr("ry", 20);


  - Line : x1, y1, x2, y2

   + stroke-width : 넓이 지정

    + stroke : 색 지정 

var svgContainer = d3.select("body").append("svg")

                                    .attr("width", 200)

                                    .attr("height", 200);



var line = svgContainer.append("line")

                            .attr("x1", 5)

                            .attr("y1", 5)

                            .attr("x2", 50)

                            .attr("y2", 50);


line.attr('stroke-width', 2).attr('stroke', 'green');


  - polyline, polygon : stroke-width, stroke, points (참조)

posted by 윤영식
2013. 8. 5. 17:01 Data Visualization/D3.js

http://www.dashingd3js.com/ 사이트의 D3.js 익히기 실습을 하면서 요약 정리해 본다. 



1. 셋업

  - https://github.com/mbostock/d3 가서 오른쪽 하단의 "Download Zip" 에서 파일 다운로드 한다 

  - 디렉토리 생성하고 d3.min.js 파일을 해당 디렉토리에 copy하고 간단한 HTML 파일 하나 만들면 준비 끝 (hello.html)

<!DOCTYPE html>

<html>

  <head>

  <script type="text/javascript" src="d3.min.js"></script>

  </head>

  <body>

    <p>Hello!</p>

  </body>

</html>



2. DOM 조작하기 

  - DOM 을 조작하여 Circle을 그린다 (참조)

  - d3는 selector를 제공하여 tag, attribute, style 등을 제어할 수 있다 (jQuery처럼)

  - Chrome Dev Tools의 console을 통해서 조작한다 

  - append : child tag 추가, attr : attribute 추가

d3.select("body").append("svg").attr('width', 50).attr('height', 50).append('circle').attr('cx', 25).attr('cy', 25).attr('r', 25).style('fill', 'orange');

  - 결과 : 오랜지색 원을 동적으로 생성함 



3. Data와 DOM 바인딩하기

  - data 메소드를 이용한 DOM과 Data의 바인딩 (참조)

  - 코드 : data(<data>).enter() 한쌍의 구문을 사용 

var theData = [1,2,3];

var p = d3.select('body').selectAll('p').data(theData).enter().append('p').text('dowon');

  - selectAll에서 Data와 바인딩 될때 empty selection 일 경우 enter()를 통해서 바인딩이 가능토록 한다 

  - data 메소드는 theData에서 1 번째는 첫번째 p tag를 2 번째는 두번째 p tag와 맵핑된다 

  - virtual selection에는 enter, update, exit 가 있다 

    + enter : missing element 와 data binding

    + update : 기존 element 와 data binding

    + exit : 맨끝에것 제거 

  - 즉, enter를 하게 되면 virtual selection의 객체 레퍼런스가 return되어 append, attr, style등의 조작이 가능해 진다 


  - 그렇다면 데이터 1, 2, 3 의 숫자 값은 어디로 갔을까? 

    + __data__ 프러퍼티가 p tag 밑으로 추가되었고 해당 속성에 값이 할당되어 있다 

    + 이것을 Binding Data to DOM Element 라고 부른다 



4. 데이터를 엑세스하여 사용하기 

  - callback function을 등록한다 (참조)

var theData = [11,222,567];

var p = d3.select('body').selectAll('p').data(theData).enter().append('p').text(function(d) { return d;});

  - 의미 : variableName의 값으로 tag의 __data__ 속성값을 갖는다. functionName은 생략하여 anonymous function으로 등록 가능하다

1function functionName (variableName) {
2  return variableName;
3}

  -  결과


다음 실습은 실제 데이터를 가지고 다양한 모양을 그려본다


<참조>

  - DashingD3js.com

posted by 윤영식
2013. 8. 2. 16:43 Data Visualization/D3.js

만들고 있는 솔루션이 기본 Highcharts를 사용하고 있다. 다른 Javascript Chart & Data Visualization Framwork에는 어떤 것들이 있는지 찾고 정리해 본다



1. Chart

  - Chart를 표현하는 다양한 Javascript가 존재한다

    + 11-javascript-toolkit-for-creating-charts-and-graphs/

  - jqWidgets : http://www.jqwidgets.com/

    + 다양한 차트와 컴포넌트를 제공한다 with jquery

  - jQuery Top 5 chart component

    + 5 Top Chart

  - Morris.js : http://www.oesmith.co.uk/morris.js/

    + 깔끔한 UI가 인상적이다

    + SVG 사용

  - xChart.jshttp://tenxer.github.io/xcharts/

    + Morris.js 와 유사하지만 좀 더 dynamic 차트 

    + SVG 사용

  - Envision.js : http://humblesoftware.com/envision/

    + 모바일에서 보여주기 좋다

    + 실시간 라인차트 존재

    + Canvas 사용

  - flotr2 : http://humblesoftware.com/flotr2/

    + 다양한 차트 종류 제공

    + CSS 디자인을 다시 손봐야 highchart 수준이 될듯하다 

    + Canvas 사용

  - Dygraphs : http://dygraphs.com/

    + 다양한 라인차트 제공

    + Canvas 사용

  - smoothie : http://smoothiecharts.org/

    + envision.js 와 유사함

    + 나름의 옵션을 가지고 있음. option ui builder 제공

    + 실시간 라인차트 제공

    + Canvas 사용

  - Rickshaw : http://code.shutterstock.com/rickshaw/

    + d3.js 프레임워크를 기반으로 chart를 제공

    + 예제가 안보임 (버그가 있는듯...)

    + SVG 사용

  - NVD3.js : http://nvd3.org/

    + rickshaw와 같은 d3.js 를 사용한 chart를 제공

    + SVG 사용

  - CanvasXpress : http://www.canvasxpress.org/

    + Canvas 사용

  - g.Raphaeljshttp://g.raphaeljs.com/

    + Raphael.js 프레임워크를 이용한 차트

    + SVG & VML 사용

  - jQuery Sparkline : http://omnipotent.net/jquery.sparkline/#s-about

    + Canvas 사용



2. Javascript Data Visualization Framework

  - Framework 선택시 가장 중요한 것은 Canvas 로 할 것인가? SVG로 할 것인가이다

    + Canvas or SVG 각각 특징

    + Canvas & SVG 비교

A Comparison of Canvas and SVG

Canvas

SVG
Pixel-based (canvas is essentially an image element with a drawing API) Object Model-based (SVG elements are similar to HTML elements)
Single HTML element similar to <img> in behavior Multiple graphical elements which become part of the Document Object Model (DOM)
Visual presentation created and modified programmatically through script Visual presentation created with markup and modified by CSS or programmatically through script
Event model/user interaction is coarse—at the canvas element only; interactions must be manually programmed from mouse coordinates Event model/user interaction is object-based at the level of primitive graphic elements—lines, rectangles, path s
API does not support accessibility; markup-based techniques must be used in addition to canvas SVG markup and object model directly supports accessibility




  - Raphael, Pager, Processing 기능 및 성능 비교 

    + 많은 양의 데이터를 실시간으로 표현하고자 한다면 Canvas,

       데이터량이 적고 분석이나 상호작용하는 차트를 원하면 SVG를 선택한다

    + Raphael.jshttp://raphaeljs.com/

       > SVG & VML 사용

       > NHN Chart 만들기 SlideShare

    + Pager.js : http://paperjs.org

       > Canvas 사용

       > Data Visualiztion 전용 프레임워크

       > 게임제작 또는 동적 차트를 만들기 좋음

       > 지돌스타님의 소개

    + Processingjs : http://processingjs.org/

       > Canvas 사용

       


  - D3.js : http://d3js.org/

    + SVG 사용

    + Data Driven Document = D3

    + D3로 구현된 다양한 Chart와 Visualization 사이트

  - DC.js : http://nickqizhu.github.io/dc.js/

    + D3.js 와 Square의 Crossfilter를 이용

    + Dimensional Charting Framework 

    + 차트끼리의 Interactive를 통하여 빠른 조회를 제공

    + 통계 조회화면 만드는데 적합

  - InfoVis : http://philogb.github.io/jit/index.html

    + Interactive Data Visualization Toolkit

    + Canvas 사용

  - Protovis : http://mbostock.github.io/protovis/

    + Graphical Visualization Toolkit

    + SVG 사용



3. Dashboard & UI Builder

  - 차트를 통하여 나오는 결과물은 대시보드!

    + Javascript Dashboard Framework

  - JointJS : Diagram을 그리는 Javascript framework

    + http://www.jointjs.com/

  - Draw.io : SVG를 이용한 draw builder

    + https://www.draw.io/

  - Tiggzi.com : https://appery.io/

    + 모바일 웹화면을 만드는 SaaS 기반 UI Builder

  - ZingChart : http://www.zingchart.com/builder/

    + Web 기반 Chart Builder

  - 01.org : https://01.org/rib/

    + Rapid Interface Builder

    + 모바일 웹화면 만들기 : https://01.org/rib/online/ (크롬만 가능)

  - Froont : http://froont.com/

    + 웹사이트를 만들어 주는 UI Builder



<참조>

  - 10-javascript-canvas-frameworks

  - 20-popular-javascript-charts-graphics-library

  - 13-useful-javascript-solutions-for-charts-and-graphs

  - 10-awesome-data-visualization-tools-for-the-web

  - 20 best tools data visualization

  - 지돌스타님의 Canvas framework 소개

  - D3 창시자 mbostock blog

  - D3로 차트 만드는 방법

'Data Visualization > D3.js' 카테고리의 다른 글

[D3.js] Bar Chart 만들기  (0) 2015.08.20
[D3.js] 배우는 방법  (1) 2013.08.06
[D3.js] DashingD3js.com 실습 - 4  (0) 2013.08.06
[D3.js] DashingD3js.com 실습 - 2  (0) 2013.08.05
[D3.js] DashingD3js.com 실습 - 1  (0) 2013.08.05
posted by 윤영식
prev 1 next