PROGRAMMING/Web

D3.js를 활용한 정보시각화

yuujoeng 2022. 10. 2. 00:35

1 데이터 시각화

(1) 정의

  - 데이터 분석 결과를 쉽게 이해할 수 있도록 시각적으로 표현, 전달되는 과정

  - 데이터를 활용하여 수치 안에 숨겨진 인사이트를 발견하게 함

 

(2) 비용이 더 적은 방법

  - scale-up: 인프라 업그레이드, 큰 파자 시키기

  - scale-out: 인프라 추가와 확장, 작은 피자 여러판 시키기

 

(3) 데이터 파이프라인

  - 데이터의 수집 > 저장 > 처리 > 분석 > 시각화

 

(4) HCI

  - Human Computer interaction

  - 사람과 컴퓨터의 상호작용에 대한 연구하는 학문의 한 분야

  - 목표: 사용자의 최적의 경험(UX) 제공

 

2 D3.js

(1) D3

  - Data Driven Documents

  - 데이터 기반의 문서를 다루는 JS 라이브러리

  - SVG: 2차원 벡터 그래픽 배열을 사용, 안깨짐, 용량 작음

 

D3.js - Data-Driven Documents

D3 is a JavaScript library for visualizing data with HTML, SVG, and CSS.

d3js.org

 

The D3 Graph Gallery – Simple charts made in d3.js

The D3 graph gallery displays hundreds of charts made with D3.js, always providing the reproducible code.

d3-graph-gallery.com

  

(2) DOM

  - 문서 내의 모든 요소를 정의하고 이를 부모 자식 형태의 트리 형태로 나타냄

  - XML HTML 등에 접근하기 쉽게 하는 인터페이스

  - D3 라이브러리를 사용하여 DOM API의 소스코드를 간소화할 수 있음

 

(3) 자주 쓰이는 함수

  - Loading : 데이터 불러오기

  - Selecting-Binding

     * select&selectAll > selection 객체 return 

     * selectAll("div").data("number") > div를 selection 객체로 뽑아서 각각에 number를 붙이기

     * 데이터 개수와 element 개수가 맞지 않으면? 데이터 기준으로 알아서 맞춰주는 join()

  - Transform : 그래프의 유형 결정, 위치 지정 등

     * domain([1, 2]) > 정의역 1부터 2까지 줄여 / range 치역ㅁ

  - Transition 

 

3 실습예제

(1) 기본 제공 소스코드 실행 화면

- mouseover에 의해 마우스를 가져가면 바가 Black으로 변하지만 돌아오지 않음 

// Bar
  svg.selectAll("myRect")
    .data(data)
    .enter()
    .append("rect")
    .attr("x", x(0) )
    .attr("y", function(d) { return y(d.Country); })
    .attr("width", function(d) { return x(d.Value); })
    .attr("height", y.bandwidth() )
    .attr("fill", "#69b3a2")
    .on("mouseover", mouseover)

})

let mouseover = function(d) {
    d3.select(this)
      .style("fill", "black");
}

 

(2) mouseout을 적용시켜 돌아오도록 설정

    .on("mouseout", mouseout)
    .on("onclick", onclick)

})

let mouseover = function(d) {
    d3.select(this)
      .style("fill", "black");
}

// 1. mouseout
let mouseout = function(d) {
  d3.select(this)
    .style("fill", "#69b3a2");
}

 

(3) 가로축 세로축 반전

// 3. xy축 변경
  // X축
  var x = d3.scaleLinear()
    .domain([0, 13000])
    .range([ 0, width]);
  svg.append("g")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x))
    .selectAll("text")
      .attr("transform", "translate(-10,0)rotate(-45)")
      .style("text-anchor", "end");

  // Y축
  var y = d3.scaleBand()
    .range([ 0, height ])
    .domain(data.map(function(d) { return d.Country; }))
    .padding(.1);
  svg.append("g")
    .call(d3.axisLeft(y))

  // Bar
  svg.selectAll("myRect")
    .data(data)
    .enter()
    .append("rect")
    .attr("x", x(0) )
    .attr("y", function(d) { return y(d.Country); })
    .attr("width", function(d) { return x(d.Value); })
    .attr("height", y.bandwidth() )
    .attr("fill", "#69b3a2")
    .on("mouseover", mouseover)
    .on("mouseout", mouseout)
    .on("onclick", onclick)

})