D3.js 
D3(Data-Driven Documents) chart library 


* d3 /d3
https://github.com/d3/d3  - 102k
    - v7.6.1 , 22-07-04
https://d3js.org/

    - API 레퍼런스
https://github.com/d3/d3/blob/main/API.md


    - 매뉴얼
https://www.d3indepth.com/introduction/  <=====


//-----------------------------------------------------------------------------
< 기본 사용법 >

// Update - 존재하는 노드 변경(기본 동작)
var p = d3.select("body")
  .selectAll("p")
  .data([4, 8, 15, 16, 23, 42])
    .text(function(d) { return d; });


// Entetr - 생성 
p.enter().append("p")
    .text(function(d) { return d; });


// Exit - 데이터를 적용하고 남은 노드가 있다면 나머지 삭제
p.exit().remove();



//-----------------------------------------------------------------------------
< 사용법 >

* Selections
https://www.d3indepth.com/selections/

 

   <svg>
        <circle r='30' />
        <circle r='50' />
    </svg>
 

//-------------------------------------
    - 속성 변경
d3.selectAll('circle')
  .attr('cx', function(d, i) {
    return i * 100;
  });

    - 이벤트
d3.selectAll('circle')
  .on('click', function(e, d) {
    d3.select(this)
      .style('fill', 'orange');
  });


    - 추가 append (맨나중)
d3.selectAll('g.item')
  .append('text')
  .text('A');

   - 추가 insert (맨처음)
d3.selectAll('g.item')
  .insert('text', 'circle')
  .text('A');

    - 제거
d3.selectAll('circle')
  .remove();


//-------------------------------------
Data Join
https://www.d3indepth.com/datajoins/

<svg>
        <g class="chart">
        </g>
    </svg>

let myData = [40, 10, 20, 60, 30];

    d3.select('.chart')
        .selectAll('circle')
        .data(myData)
        .join('circle') //  다음과 동일    //.enter().append('circle')
        .attr('cx', function (d, i) {
            return i * 100;
        })
        .attr('cy', 50)
        .attr('r', 40)
        .style('fill', 'orange');

//-------------------------------------
    - enter, update, exit
.join(
  function(enter) { // 생성
    return enter
      .append('circle')
      .style('opacity', 0);
  },
  function(update) { // 변경
    return update
      .style('opacity', 1);
  },
  function(exit) {
    return exit.remove(); // 나가기(나머지 노드 삭제)
  }
)

//-------------------------------------
<  스케일 >
https://www.d3indepth.com/scales/

scale : 수치형 값을 다른 범위의 수치형 값으로 매핑
domain : 입력범위 , (입력 자료, number, date , category)
range : 출력 범위 (표현 좌표, coordinate,  colour,  length ,  radius)


* 지원 스케일 종류
https://github.com/d3/d3/blob/main/API.md#scales-d3-scale
    - Continuous Scales
scaleLinear, scalePow, scaleSqrt , scaleLog , scaleSymlog , scaleIdentity 
scaleRadial, scaleTime , scaleUtc 

    - Sequential Scales
scaleSequential , scaleSequentialLog , ...

    - Diverging Scales
scaleDiverging , scaleDivergingLog , ...

    - Quantize Scales
scaleQuantize , scaleQuantile , scaleThreshold 

    - Ordinal Scales
scaleOrdinal , scaleImplicit , scaleBand , scalePoint 



//-------------------------------------
입력 데이터 =  [ 0, 2, 3, 5, 7.5, 9, 10 ]

let myScale = d3.scaleLinear()
  .domain([0, 10])
  .range([0, 600]);

    - 결과
myScale(0);   // returns 0
myScale(2);   // returns 120
myScale(3);   // returns 180
...
myScale(10);  // returns 600



//-------------------------------------
* D3 Shapes
https://www.d3indepth.com/shapes/
https://github.com/d3/d3/blob/main/API.md#shapes-d3-shape

    지원하는 모양
line, area, stack, arc, pie, symbol , 
lineRadial - 다각형
areaRadial -
curveBasis , curveLinear , link 

//-------------------------------------
     <svg width="700" height="200">
        <path></path>
    </svg>

var points = [
            [0, 80],
            [100, 100],
            [200, 30],
            [300, 50],
            [400, 40],
            [500, 80]
        ];        
        d3.select('path')
            .attr('d', d3.line()(points));


//-------------------------------------


<svg width="500" height="500">
        <g id="left" transform="translate(30, 40)"></g>
        <g id="right" transform="translate(450, 40)"></g>
        <g id="top" transform="translate(40, 30)"></g>
        <g id="bottom" transform="translate(40, 450)"></g>
    </svg>

let scale = d3.scaleLinear().domain([0, 100]).range([0, 400]);

let axisLeft = d3.axisLeft(scale);
let axisRight = d3.axisRight(scale);
let axisTop = d3.axisTop(scale);
let axisBottom = d3.axisBottom(scale);

d3.select('#left').call(axisLeft);
d3.select('#right').call(axisRight);
d3.select('#top').call(axisTop);
d3.select('#bottom').call(axisBottom);

//-----------------------------------------------------------------------------
* 자료 파일 읽기

function convertRow(d) {
  return {
    rank: +d.rank,
    workers: +d.workers,
    name: d.company,
    state: d.state_l,
    city: d.city,
    growth: +d.growth,
    revenue: +d.revenue,
    sector: d.industry
  }
}

d3.csv('https://assets.codepen.io/2814973/Inc5000+Company+List_2014-top250.csv', convertRow)
  .then(function(data) {
    console.log(data);
  });

//-------------------------------------
*  변환(transition, 애니메이션)
https://www.d3indepth.com/transitions/
<svg width="400" height="200">
            <circle />
</svg>

d3.selectAll("circle")
            .data([4, 8, 15, 16, 23, 42])
            .transition()
            .duration(1750)
            .delay(function (d, i) { return i * 10; })
            .attr("r", function (d) {
                return Math.sqrt(d * 10);
            });



//-------------------------------------
계층적 데이터
https://www.d3indepth.com/hierarchies/
treemaps , packed circles, sunburst charts




//-------------------------------------
Chord Diagram
    상호 관계 표시
https://www.d3indepth.com/chords/




//-------------------------------------
* D3 Force layout
https://www.d3indepth.com/force-layout/
    물리 규칙 적용 : 인력, 척력, 




//-----------------------------------------------------------------------------
* 수학함수
https://github.com/d3/d3/blob/main/API.md#arrays-d3-array
    - 배열, 통계, 검색, 반복, 집합



//-----------------------------------------------------------------------------
// 참고
https://github.com/d3/d3/wiki/Tutorials

https://www.tutorialspoint.com/d3js/d3js_working_example.htm

https://blog.risingstack.com/d3-js-tutorial-bar-charts-with-javascript/

https://d3-graph-gallery.com/intro_d3js.html

//-------------------------------------
예제
https://github.com/d3/d3/wiki/Gallery

https://www.bogotobogo.com/DataVisualization/List_of_D3_Examples.php

https://observablehq.com/@d3/gallery

 

 

반응형
Posted by codens

댓글을 달아 주세요