Built with blockbuilder.org
Last active
May 6, 2017 18:02
-
-
Save meilivh/529e0872d707959f1bc2cc37145bae00 to your computer and use it in GitHub Desktop.
Update Pattern Bar Chart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
license: mit |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<head> | |
<meta charset="utf-8"> | |
<script src="https://d3js.org/d3.v4.min.js"></script> | |
<style> | |
.enter { | |
fill: green; | |
} | |
.update { | |
fill: #333; | |
} | |
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } | |
</style> | |
</head> | |
<body> | |
<div id="chart" width=1000 height=300></div> | |
<script> | |
var myData = [1,2,3,4,5,6,7,8,9,0]; | |
var svg = d3.select("#chart") | |
.append('svg') | |
.attr('width',500) | |
.attr('height',200) | |
.attr("transform", "translate(300,100)"); | |
function update(data) { | |
let BAR_WIDTH = 30; | |
var y = d3.scaleLinear() | |
.domain([0,d3.max(data)]) | |
.range([200,0]); | |
rects = svg.selectAll('rect') | |
.data(data); | |
// Update | |
rects.attr('class','update'); | |
// Enter | |
rects.enter().append('rect') | |
.attr('class','enter') | |
.attr('x',function(d,i) { | |
return i * (BAR_WIDTH+2) | |
}) | |
.attr('width',BAR_WIDTH) | |
.attr('height',200) | |
.attr('y',200) | |
.merge(rects) | |
.transition() | |
.duration(1000) | |
.attr('y', function (d,i) { | |
return y(d); | |
}); | |
rects.exit() | |
.transition() | |
.duration(1000) | |
.attr('y',200) | |
.remove(); | |
} | |
update(myData); | |
d3.interval(function(){ | |
return update(myData.slice(0,Math.random()*myData.length)); | |
}, 1500) | |
</script> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment