HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
👻
개발 기록
/
📑
강의 정리
/
📑
D3시작하기 ~ selection
📑

D3시작하기 ~ selection

Created
Nov 16, 2021 08:25 PM
Type
React
Mento
노지현님
Created By

D3

  • 자바스크립트 라이브러리.
  • 데이터 시각화에 적합한 오픈소스.
  • SVG로 이루어짐.
  • 데이터 기반으로 DOM을 다룸.
    • 다양한 데이터 포맷 처리 & import 제공.
    • HTML, SVG 웹 표준 기술을 다양하게 사용.
    • 데이터와 DOM element를 결합.
  • 다양한 그래프를 만들어낼 수 있음.

단점

  • 분석 툴이 아님.
  • 엑셀처럼 쉽고 빠르게 시각화를 만들어낼 순 없음.
  • 주요 원리 및 API를 익혀야 함.
    • notion image

D3 시작하기

👉 공식 홈페이지
👉 D3를 간단하게 사용해볼 수 있는 웹서비스
<script src="https://d3js.org/d3.v7.min.js"></script>

selection

  • D3가 DOM을 조작할 때 사용하는 기본 단위(객체).

기초 메서드

d3.select

querySelector로 DOM 요소를 찾음. 인자와 일치한 가장 첫번째 요소로 Selection 객체 구성. 일치하는 게 없으면, 빈 배열을 가진 Selection 객체 구성.
d3.select('.footer').select('p').text()

selection.text()

selection이 가리키는 요소의 텍스트를 가져옴.

selection.attr()

selection이 가리키는 요소의 속성을 가져오거나 설정함.
const myCircle = d3.select('cirlce'); myCircle.attr('fill', 'red');

selection.style()

selection이 가리키는 요소의 스타일을 설정.
d3.select('p').style('font-family', 'Arial');

selection.append()

selection이 가리키는 요소의 자식으로 요소를 추가. 생성된 요소를 반환하기 때문에 코드 마지막에 넣거나 변수 활용을 권장.
d3.select('#header').append('p').text('Add text').style('font-style', 'italic');

selection.remove()

selection이 가리키는 요소를 DOM에서 삭제. 제거된 요소를 반환함.
d3.selectAll('div').remove();

메서드를 사용해 코드 수정하기

notion image
notion image
  • 직접 넣었던 영화 이름과 관객 수는 따로 배열로 빼는 것이 좋음.
    • notion image
  • 간격이 일정하게 커지고 있다면 그 간격을 변수로 만들어 재사용할 수 있음.
    • notion image

알아두면 좋은 메서드

selection.insert()

  • 새로운 요소를 삽입함.
  • 지정된 위치에 추가하거나, 지정하지 않으면 선택한 selection의 자식으로 새 요소를 추가함.
function insertBox() { d3.select('#box').insert('div').classed('box aqua-box', true); }

selection.clone()

  • 선택한 모든 요소를 복제하거, 선택한 요소 바로 뒤에 삽입함.
  • 두번째 인자로 true를 전달하면, 선택한 요소의 모든 하위 노드들도 복제됨.
  • 반환할 땐 [선택한 기존 selection & 새로 복제 생성된 요소]를 반환함.
function insertBox() { d3.selectAll('#box').clone(false).classed('box aqua-box', true); }
notion image

selection.raise()

  • selection의 요소를 해당 부모의 마지막 자식으로 DOM에 다시 삽입함.
function raise() { d3.select('#box').selectAll('.pink,.violet').raise(); d3.select('#box') .selectAll('circle') .attr('cx', (d,i) => 30 + (i * 60)); }
notion image

selection.lower()

  • selection의 요소를 해당 부모의 첫번째 자식으로 DOM에 다시 삽입함.
function raise() { d3.select('#box').selectAll('.pink,.violet').lower(); d3.select('#box') .selectAll('circle') .attr('cx', (d,i) => 30 + (i * 60)); }
notion image

selection.sort()

  • DOM에서 compare function을 기반으로 선택한 selection의 위치를 변경함.
  • compare function을 수행한 다음 새로 정렬된 순서로 요소들을 DOM에 다시 삽입함.
  • compare function은 직접 정의하거나, D3에서 제공하는 비교자들을 사용할 수 있음.
d3.select('graph') .selectAll('rect') .sort((a, b) => d3.ascending(a.population, b.population)) .attr('y' (d, i) => i * 20); d3.select('graph') .selectAll('text') .sort((a, b) => d3.ascending(a.population, b.population)) .attr('y' (d, i) => i * 20 + 17);

selection.nodes()

  • 해당 selection의 모든 요소를 배열로 반환함.
  • selection.node()는 해당 selection의 첫 번째 요소를 반환함.
    • selection이 비어 있으면 null을 반환함.
function getNode() { const barRect = d3.select('#bargraph').selectAll('rect') console.log(barRect.nodes()); //모든 rect 요소를 반환 console.log(barRect.node()); //첫번째 rect 요소를 반환 }

selection.call()

  • 인수로 전달된 function을 실행함.
  • 여러 selection에 실행해야 하는 일련의 처리가 있는 경우 유용함.
function addElementWithCall() { d3.selectAll('#callBoxes > div').call(addElements, 1); }