D3.js 바 그래프 그리기(div), 데이터 수정
[다운로드]
http://d3js.org/download/ (d3.js)
http://jquery.com/ (jquery.js)
[index.html]
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>D3 Test</title>
<script type="text/javascript" src="../javascripts/lib/d3.js"></script>
<link rel="stylesheet" href="../stylesheets/style.css">
</head>
<body>
<button class="btn adddata">add data</button>
<button class="btn removedata">remove data</button>
<button class="btn changedata">change data</button>
<br><br>
<div id="demo"></div>
<script src="../javascripts/lib/jquery.min.js"></script>
<script type="text/javascript" src="../javascripts/d3sample.js"></script>
</body>
</html>
[d3sample.js]
// Your beautiful D3 code will go here
var dataset = [ 1, 2, 3, 4, 5 ];
var targetDiv;
$(document).ready(function () {
targetDiv = d3.select("#demo"); //DOM에서 demo div를 찾음
var refresh = function () {
var divs = targetDiv.selectAll("div") //DOM에서 모든 div를 찾음. 아직 존재하지 않으면 빈 selection을 반환하며, 빈 selection은 앞으로 존재하게 될 div들이라고 생각함
.data(dataset); //데이터 값을 세고 파싱함. 데이터 수에 따라 아래 메서드체인이 반복해서 실행됨
divs.enter() //data-bound element를 생성함.
.append("div") //enter에 의해 생성된 placeholder selection을 받고 DOM에 div를 삽입함.
.attr("class", "bar") //삽입되는 div에 class 속성을 추가함
.transition()
.style("height",function (d) { //삽입되는 div에 style 속성을 추가하며 내용은 height에 각 data (d)의 * 5 px로 계산하여 추가함
return d*10+"px";
});
divs.transition() //data-bound element를 생성함. enter()와 update()가 있음
.style("height",function (d) { //삽입되는 div에 style 속성을 추가하며 내용은 height에 각 data (d)의 * 5 px로 계산하여 추가함
return d*10+"px";
});
divs.exit()
.remove()
};
refresh();
$('.adddata').on('click',function () {
dataset.push(Math.floor(Math.random()*10+1));
refresh();
});
$('.removedata').on('click',function () {
dataset.splice(Math.floor(Math.random()*dataset.length),1);
refresh();
});
$('.changedata').on('click',function () {
dataset = [ 8, 25, 14, 23, 19 ];
//dataset[2] = 20; //가능
refresh();
});
});
[style.css]
.btn{
width: 100px;
height: 30px;
}
div.bar{
display: inline-block;
width: 20px;
height: 75px;
background-color: teal;
margin-right: 2px;
}
'Development > D3js' 카테고리의 다른 글
Interactive General Update Pattern (0) | 2017.09.04 |
---|---|
D3.js에서 svg 사용하기 (0) | 2017.04.24 |
D3.js 개요 및 핵심 정리 (0) | 2017.04.24 |
Scatter (svg) 그래프 그리기, Transition (0) | 2017.04.20 |
D3.js 바 그래프 그리기(svg), 데이터 수정 (0) | 2017.04.12 |