D3_js

[D3.js] 축_ aXis

vhxpffltm 2019. 8. 15. 13:17
반응형

 

D3.js  :  축

축은 척도와 형태가 거의 유사하다. 축은 우리가 정의한 파라미터를 가진 함수이며 척도와 다르게 축 함수를 호출하면 어떤 값을 반환하는 대신에 선, 라벨, 구분자를 가진 시각적 요소가 생성된다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>D3: A simple, unstyled axis</title>
        <script type="text/javascript" src="https://d3js.org/d3.v5.js"></script>
        <style type="text/css">
            /* No style rules here yet */
        </style>
    </head>
    <body>
        <script type="text/javascript">
            var w = 500;
            var h = 300;
            var padding = 20;
            
            var dataset = [
                        [520], [48090], [25050], [10033], [33095],
                        [41012], [47544], [2567], [8521], [22088],[600,150]
        ];
            
            var xScale = d3.scaleLinear()
                                 .domain([0d3.max(dataset, function(d) { return d[0]; })])
                                 .range([padding, w - padding * 2]);
            var yScale = d3.scaleLinear()
                                 .domain([0d3.max(dataset, function(d) { return d[1]; })])
                                 .range([h - padding, padding]);
            var aScale = d3.scaleSqrt()
                                 .domain([0d3.max(dataset, function(d) { return d[1]; })])
                                 .range([010]);
            //축 정의
            var xAxis = d3.axisBottom()
                            .scale(xScale);
                            
            
            var svg = d3.select("body")
                        .append("svg")
                        .attr("width", w)
                        .attr("height", h);
            
            svg.selectAll("circle")
               .data(dataset)
               .enter()
               .append("circle")
               .attr("cx"function(d) {
                       return xScale(d[0]);
               })
               .attr("cy"function(d) {
                       return yScale(d[1]);
               })
               .attr("r"function(d) {
                       return aScale(d[1]);
               });
        
            svg.selectAll("text")
               .data(dataset)
               .enter()
               .append("text")
               .text(function(d) {
                       return d[0+ "," + d[1];
               })
               .attr("x"function(d) {
                       return xScale(d[0]);
               })
               .attr("y"function(d) {
                       return yScale(d[1]);
               })
               .attr("font-family""sans-serif")
               .attr("font-size""11px")
               .attr("fill""red");
            
            
            //축 생성
            svg.append("g")
                .attr("class""axis")
                .attr("transform""translate(0," + (h - padding) + ")")
                .call(xAxis);
        </script>
    </body>
</html>
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

 

위의 코드에서 

var xAxis = d3.axisBottom()

                            .scale(xScale);

...

svg.append("g")

                .attr("class""axis")

                .attr("transform""translate(0," + (h - padding) + ")")

                .call(xAxis);

 

 

축을 정의하고 축을 생성한다. 축을 생성하기 위해 선과 라벨을 SVG에 넣으려면 만든 xAxis 함수를 호출해야한다. 그 함수가 call() 함수이다. 

 

위 코드에서 하는 일은 DOM의 SVG 이미지를 뜻하는 svg변수를 참조한다. 그리고 append를 통해 'g' 문서요소를 추가한다. 'g' 문서요소는 그룹을 뜻하며 눈에 보이지 않는다. 주로 시각적 요소 랜더링을 위한 트랜스폼을 결정하거나 컨테이너 역할을 한다.

 

call은 메서드 체인 앞단의 선택물을 가져와 함수로 건네준다. 여기서 선택물은 'g' 이다.  위의 attr 2줄을 지우면 상단에 X축이 생성된것을 확인할 수 있을 것이다. 

 

'transform' 이 적용되면 축이 아래로 이동할 것이다. g 그룹을 (x,y) 값만큼 이동하게 될 것이다. 여기서 g그룹은 class axis이다.

 

눈금

눈금은 정보 전달 창구 역할을 할 수 있다. D3에서는 xscale값을 확인하여 자동으로 구분자의 개수와 간격을 결정한다. 눈금자 수는 ticks()를 사용하여 지정할 수 있다.

 

var xAxis = d3.axisBottom()

                            .scale(xScale);

 

위 코드에 .ticks(5)  를 추가하면 우리가 원하는 눈금자를 5개로 설정할 수 있으며 그 간격을 자동으로 맞춰준다.

 

이때까자의 결과를 보면 아래와 같다.

 

 

그룹 'g'가 어떻게 이루어졌는지 확인하면 좋다. 이제 Y축도 만들어보자 똑같이 아래의 코드를 추가하면 된다.

 

1
2
3
4
5
6
7
var yAxis = d3.axisLeft()
                   .scale(yScale)
                   .ticks(5);
                .attr("class""axis")
                .attr("transform""translate(" + padding + ",0)")
                .call(yAxis);
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

 

정의에서 axisLeft()를 부르고 호출할 때 이동 좌표만 수정하면 쉽게 Y축을 생성할 수 있다. 결과는 직접 확인해보면 좋을 것 같다.

 

라벨 포매팅(Formatting)

데이터가 정수가 아니라 지저분 할 수 있다. 이를 위해 축의 라벨을 포매팅한다. 예로 소수점 아래 3자리나 백분율로 시각화하는 경우를 생각할 수 있다. 

tickformat() 함수를 이용하여 조절할 수 있다.

 

여기까지 진행한 코드와 결과는 아래와 같다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>D3: A simple, unstyled axis</title>
        <script type="text/javascript" src="https://d3js.org/d3.v5.js"></script>
        <style type="text/css">
            /* No style rules here yet */
        </style>
    </head>
    <body>
        <script type="text/javascript">
            var w = 500;
            var h = 300;
            var padding = 30;
            
            var dataset = [
                        [520], [48090], [25050], [10033], [33095],
                        [41012], [47544], [2567], [8521], [22088],[600,150]
        ];
            
            var xScale = d3.scaleLinear()
                                 .domain([0d3.max(dataset, function(d) { return d[0]; })])
                                 .range([padding, w - padding * 2]);
            var yScale = d3.scaleLinear()
                                 .domain([0d3.max(dataset, function(d) { return d[1]; })])
                                 .range([h - padding, padding]);
            var aScale = d3.scaleSqrt()
                                 .domain([0d3.max(dataset, function(d) { return d[1]; })])
                                 .range([010]);
 
            var formatAsPercentage = d3.format(".1%");
            //축 정의
            var xAxis = d3.axisBottom()
                            .scale(xScale)
                            .ticks(5)
                            .tickFormat(formatAsPercentage);
            var yAxis = d3.axisLeft()
                            .scale(yScale)
                            .ticks(5)
                            .tickFormat(formatAsPercentage);
            
            var svg = d3.select("body")
                        .append("svg")
                        .attr("width", w)
                        .attr("height", h);
            
            svg.selectAll("circle")
               .data(dataset)
               .enter()
               .append("circle")
               .attr("cx"function(d) {
                       return xScale(d[0]);
               })
               .attr("cy"function(d) {
                       return yScale(d[1]);
               })
               .attr("r"function(d) {
                       return aScale(d[1]);
               });
            
            
            //축 생성
            svg.append("g")
                .attr("class""axis")
                .attr("transform""translate(0," + (h - padding) + ")")
                .call(xAxis);
 
            svg.append("g")
                .attr("class""axis")
                .attr("transform""translate(" + padding + ",0)")
                .call(yAxis);
        </script>
    </body>
</html>
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

 

 

반응형

'D3_js' 카테고리의 다른 글

[D3.js] 산포도 갱신, 트랜지션  (0) 2019.08.28
[D3.js] 막대 그래프 갱신, 트랜지션(trasition)  (0) 2019.08.28
[D3.js] 척도  (0) 2019.08.03
[D3.js] Scatter_산포도  (0) 2019.07.25
[D3.js] SVG를 이용한 Chart와 Circle  (0) 2019.07.19