๋ฐ์ํ
๐ ๋ชฉ๋ก
- Introduction
- Bar Chart ๋ง๋ค๊ธฐ
- Conclusion
๐ Introduction
์๋ ํ์ธ์. ์ค๋์ ์ง๋๋ฒ ์๊ฐ ํ๋ d3 ์ ๊ธฐ๋ณธ์ ํตํด bar chart๋ฅผ ํ๋ฒ ๊ฐ๋จํ๊ฒ ๋ง๋ค์ด ๋ณด๊ฒ ์ต๋๋ค.
๐ Bar Chart ๋ง๋ค๊ธฐ
๋จผ์ data๋ฅผ ์๊ฐ ํ ๊ฒ์. data๋ csvํ์ผ์ ์ ์ฅ์ด ๋์ด์์ต๋๋ค.
"month","revenue","profit"
"January","13432","8342"
"February","19342","10342"
"March","17443","15423"
"April","26342","18432"
"May","34213","29434"
"June","50321","45343"
"July","54273","47452
์ด์ ์ ์์ ์ผ๋ก ์ฝ๋๋ฅผ ํ๋ฒ ๋ณผ๊น์?
const MARGIN = { LEFT: 100, RIGHT: 10, TOP: 10, BOTTOM: 130 };
const WIDTH = 600 - MARGIN.LEFT - MARGIN.RIGHT;
const HEIGHT = 400 - MARGIN.TOP - MARGIN.BOTTOM;
// csv ํ์ผ์ ๋ถ๋ฌ์ต๋๋ค.
d3.csv("data/revenues.csv").then((data) => {
// CONVERT DATA REVENUE TO NUMBER
// data์ revenue๊ฐ string์ผ๋ก ๋์ด์์ด์ number๋ก parsing์ ํด์ค์
data.forEach((d) => {
d.revenue = Number(d.revenue);
});
// CREATE SVG
const svg = d3
.select("#chart-area")
.append("svg")
.attr("width", WIDTH + MARGIN.LEFT + MARGIN.RIGHT)
.attr("height", HEIGHT + MARGIN.TOP + MARGIN.BOTTOM);
// APPEND G FOR MARGIN
const g = svg
.append("g")
.attr("transform", `translate(${MARGIN.LEFT}, ${MARGIN.TOP})`);
// CREATE X SCALE
const x = d3
.scaleBand()
.domain(data.map((d) => d.month))
.range([0, WIDTH])
.paddingInner(0.3)
.paddingOuter(0.2);
// CREATE Y SCALE
const y = d3
.scaleLinear()
.domain([0, d3.max(data, (d) => d.revenue)])
.range([HEIGHT, 0]);
// CREATE X-AXIS CALL
const xAxisCall = d3.axisBottom(x);
// APPEND X-AXIS
g.append("g").call(xAxisCall).attr("transform", `translate(0, ${HEIGHT})`);
// CREATE Y-AXIS CALL
const yAxisCall = d3.axisLeft(y).tickFormat((d) => `$${d}`);
// APPEND Y-AXIS
g.append("g").call(yAxisCall);
// CREATE X LABEL
g.append("text")
.attr("x", WIDTH / 2)
.attr("y", HEIGHT + 50)
.attr("text-anchor", "middle")
.attr("font-size", "20px")
.text("Month");
// CREATE Y LABEL
g.append("text")
.attr("x", -(HEIGHT / 2))
.attr("y", -60)
.attr("transform", "rotate(-90)")
.attr("text-anchor", "middle")
.attr("font-size", "20px")
.text("Revenue");
// CREATE BAR
const revenues = g.selectAll("rect").data(data);
revenues
.enter()
.append("rect")
.attr("x", (d) => x(d.month))
.attr("y", (d) => y(d.revenue))
.attr("width", 40)
.attr("height", (d) => HEIGHT - y(d.revenue))
.attr("fill", "gray");
});
๐ Conclusion
์ด๋ ๊ฒ ๊ฐ๋จํ๊ฒ bar chart๋ฅผ ๋ง๋ค์ด ๋ดค์ต๋๋ค. ์ด์ ์ด๊ฑธ ํ ๋๋ก ํ๋ฒ ์คํ์์ค๋ก ๋ง๋ค์ด ๋ด์ผ๊ฒ ์ด์. ๊ทธ๊ฑด ๋ ๋ค๋ฅธ ํฌ์คํ ์์ ๋ค๋ค๋ณด๋๋ก ํ๊ฒ ์ต๋๋ค. ๊ทธ๋ผ ์๋ ~~ ๐
๋ฐ์ํ
'D3' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
D3 - Update pattern (0) | 2021.01.13 |
---|---|
D3 - Scale and Axes (0) | 2021.01.06 |
D3 - Baisc (0) | 2021.01.03 |