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

Publication

Category

Recent Post

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 윤영식