# D3.js

D3(Data-Driven Documents)๋Š” ๋ฐ์ดํ„ฐ๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ๋™์ ์ด๊ณ  ์ธํ„ฐ๋ž™ํ‹ฐ๋ธŒํ•œ ์ •๋ณด ์‹œ๊ฐํ™”๋ฅผ ๊ตฌํ˜„ํ•˜๊ธฐ ์œ„ํ•œ JavaScript(์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ)๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์ž…๋‹ˆ๋‹ค.

# SVG ์‚ฌ์šฉ

SVG์™€ HTML5, CSS ๋“ฑ ์›น ํ‘œ์ค€์— ๊ธฐ๋ฐ˜ํ•ด ๊ตฌํ˜„๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค.

SVG(Scalable Vector Graphics)๋ž€ ๊ทธ๋ž˜ํ”ฝ์„ ๋งˆํฌ์—… ํ•˜๊ธฐ ์œ„ํ•œ ์–ธ์–ด๋กœ ์•„๋ž˜ ๋ทฐ ๋กœ๊ณ ์™€ ๊ฐ™์€ ๊ทธ๋ž˜ํ”ฝ ๋“ฑ์„ ํ‘œํ˜„ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. HTML์ด ํ—ค๋”, ๋ฌธ๋‹จ, ํ‘œ์™€ ๊ฐ™์€ ์—˜๋ฆฌ๋จผํŠธ(Element)๋ฅผ ์ œ๊ณตํ•˜๋Š” ๊ฒƒ์ฒ˜๋Ÿผ SVG๋„ ์›, ์‚ฌ๊ฐํ˜•, ๊ฐ„๋‹จํ•œ ๊ณก์„ ๊ณผ ๋ณต์žกํ•œ ๊ณก์„ ์„ ๊ทธ๋ฆด ์ˆ˜ ์žˆ๋Š” ์—˜๋ฆฌ๋จผํŠธ๋“ค์„ ์ œ๊ณตํ•ฉ๋‹ˆ๋‹ค.

TIP

SVG์— ๋Œ€ํ•œ ๊ธฐ์ˆ ์ ์ธ ์„ธ๋ถ€์‚ฌํ•ญ์€ MDN ๋ฌธ์„œ (opens new window)์˜ ํŠœํ† ๋ฆฌ์–ผ์„ ํ™•์ธํ•ด ์ฃผ์„ธ์š”.

# ๋ฐ์ดํ„ฐ ์‹œ๊ฐํ™”

๋‹ค์Œ๊ณผ ๊ฐ™์€ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ๋ฐฐ์—ด์ด ์žˆ์Šต๋‹ˆ๋‹ค. ์ด ๋ฐ์ดํ„ฐ๋ฅผ SVG์˜ ํŒจ์Šค(path) ์—˜๋ฆฌ๋จผํŠธ๋ฅผ ์‚ฌ์šฉํ•ด์„œ ์„  ๋ชจ์–‘์œผ๋กœ ์‹œ๊ฐํ™”ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

const data = [90, 72, 75, 25, 10, 92];

ํŒจ์Šค์˜ ๋ชจ์–‘์€ ํŠน์ • ์•ŒํŒŒ๋ฒณ์œผ๋กœ ์ด๋ฃจ์–ด์ง„ ๋ช…๋ น๊ณผ XY ์ขŒํ‘œ๋กœ ์ด๋ฃจ์–ด์ง„ d ์†์„ฑ์œผ๋กœ ๋งŒ๋“ค์–ด์ง€๋Š”๋ฐ, ์•„๋ž˜ ์˜ˆ์ œ์˜ "M20,45.99999999999999L112,92.80000000000001L204,85L296,215L388,254L480,40.79999999999999" ๋ฌธ์ž์—ด์ด data ๋ฐฐ์—ด ๊ฐ์ฒด๋ฅผ ์‹œ๊ฐํ™”ํ•˜๋Š”๋ฐ ์‚ฌ์šฉ๋œ ๊ฐ’์ž…๋‹ˆ๋‹ค.

<svg width="500" height="300">
    <g transform="translate(0, 0)">
        <path
            fill="none"
            stroke="#76BF8A"
            stroke-width="3"
            d="M20,45.99999999999999L112,92.80000000000001L204,85L296,215L388,254L480,40.79999999999999"
        ></path>
    </g>
</svg>

์œ„์ฒ˜๋Ÿผ ๋ฐ์ดํ„ฐ๋ฅผ SVG ๊ทธ๋ž˜ํ”ฝ ์š”์†Œ๋กœ ์‹œ๊ฐํ™”ํ•˜๊ธฐ ์œ„ํ•ด ์‚ฌ์šฉ๋˜๋Š” ์†์„ฑ ๊ฐ’๋“ค์„ ๊ณ„์‚ฐํ•  ๋•Œ D3์—์„œ ์ œ๊ณตํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

const xScale = d3
  .scaleLinear()
  .range([20, 480])
  .domain(d3.extent(data, (d, i) => i));

const yScale = d3.scaleLinear().range([280, 20]).domain([0, 100]);

const line = d3
  .line()
  .x((d, i) => xScale(i))
  .y((d) => yScale(d));

console.log(line(data)) // M20,45.99999999999999L112,92.80000000000001L204,85L296,215L388,254L480,40.79999999999999

# ๋ฌธ์„œ ์กฐ์ž‘

jQuery(์ œ์ด์ฟผ๋ฆฌ)์™€ ์œ ์‚ฌํ•œ ๋ฐฉ์‹์œผ๋กœ ๋”์— ์ ‘๊ทผํ•ด์„œ ๊ณ„์‚ฐ๋œ ๋ฐ์ดํ„ฐ ๊ฐ’์„ ๋ฐ”์ธ๋”ฉํ•˜๊ณ  ์Šคํƒ€์ผ์„ ์„ค์ •ํ•˜๊ณ  ํ™”๋ฉด์— ๋ Œ๋”๋ง(rendering) ํ•ฉ๋‹ˆ๋‹ค.


const svg = d3.select('svg')
    .attr('width', 500)
    .attr('height', 300)

svg
    .append('path')
    .datum(data)
    .attr("fill", "none")
    .attr("stroke", "#76BF8A")
    .attr("stroke-width", 3)
    .attr("d", line);

# ์˜ˆ์ œ

์‹คํ–‰ํ•ด ๋ณด๊ธฐ (opens new window)