D3.js 바 그래프 그리기(svg), 데이터 수정
svg : Scalable Vector Graphics
[다운로드]
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="svgdemo"></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 targetSVG;
var w = 300;
var h = 300;
var barPadding = 2;
$(document).ready(function () {
targetSVG = d3.select("#svgdemo")
.append("svg")
.attr("width", w)
.attr("height", h);
var refreshSVG = function () {
d3.select("#svgdemo").selectAll("rect").remove();
d3.select("#svgdemo").selectAll("text").remove();
var rects = targetSVG.selectAll("rect")
.data(dataset);
rects.enter()
.append("rect")
.attr("x", function (d,i) { //return i*22;
return i*(w/dataset.length); //svg 전체 가로 크기를 각 데이터 길이로 나누어 넓게 사용
})
.attr("y", function (d) {
return h-d*10; //svg가 top left에서 부터 그리기 시작하기 때문에 뒤집어줌
})
.attr("width", w / dataset.length - barPadding) //.attr("width", 20)
.attr("height", function(d){
return d*10;
})
.attr("fill","teal");
rects.exit()
.remove();
var texts = targetSVG.selectAll("text")
.data(dataset);
texts.enter()
.append("text")
.text(function(d) {
return d;
})
.attr("x", function(d, i) {
return i * (w / dataset.length) + (w / dataset.length - barPadding) / 2;
})
.attr("y", function(d) {
return h - (d * 10) + 10; // +10
})
.attr("font-family", "sans-serif")
.attr("font-size", "11px")
.attr("fill", "white")
.attr("text-anchor", "middle");
texts.exit()
.remove();
};
refreshSVG();
$('.adddata').on('click',function () {
dataset.push(Math.floor(Math.random()*10+1));
refreshSVG();
});
$('.removedata').on('click',function () {
dataset.splice(Math.floor(Math.random()*dataset.length),1);
console.log(dataset);
refreshSVG();
});
$('.changedata').on('click',function () {
dataset = [ 8, 25, 14, 23, 19 ];
//dataset[2] = 20; //가능
refreshSVG();
});
});
[style.css]
.btn{
width: 100px;
height: 30px;
}
'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 바 그래프 그리기(div), 데이터 수정 (0) | 2017.04.12 |