Skip to content

Instantly share code, notes, and snippets.

@bhvaleri
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bhvaleri/9540417 to your computer and use it in GitHub Desktop.
Save bhvaleri/9540417 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>bhvaleri D3</title>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<style>
html, body { width: 100%; height: 100%; margin: 0; padding: 0; }
.bar {
display: inline-block;
width: 20px;
height: 75px;
background-color: teal;
margin-right: 2px;
}
</style>
<script type="text/javascript">
window.onload = function() {
dataset = [
{ id: 'cow', value: 5, color: 'teal' },
{ id: 'pig', value: 10, color: 'black' },
{ id: 'cat', value: 15, color: 'orange' },
{ id: 'dog', value: 20, color: 'blue' },
{ id: 'rat', value: 25, color: 'red' },
];
colors = ['teal', 'black', 'orange', 'blue', 'red'];
var w = window.innerWidth;
var h = window.innerHeight;
var svg = d3.select('body').append('svg');
svg.attr('width', w)
.attr('height', h);
d3.select(window).on('resize', function() {
w = window.innerWidth;
h = window.innerHeight;
svg.attr('width', w)
.attr('height', h);
refresh();
});
refresh = function() {
var circles = svg.selectAll('circle')
.data(dataset, function(d) { return d.id; });
// no circles yet
var newCircles = circles.enter().append('circle').attr('r', 100);
// circles for everything in dataset
newCircles.on('click', function(d) {
dataset.splice(dataset.indexOf(d), 1)
refresh();
});
// first time, this will do nothing
circles.exit().transition().duration(1000).attr('r',0).style('fill-opacity', 0).remove();
// this updates everything that remains in the DOM
circles.transition()
.style('fill', function(d) { return colors[Math.floor(Math.random() * colors.length)]})
.style('fill-opacity', function (d) { return d.value / 100; })
.attr('cx', function (d, i) {
return ((i * 50) + 25) % w;
})
.attr('cy', function(d, i) {
return 25 * (1 + Math.floor((i * 50) + 25) / w)
})
.transition()
.attr('r', function (d) {
return Math.floor(Math.random() * 50);
});
};
refresh();
setInterval(function() {
dataset.push({ id: Math.random().toString(36).slice(2), value: 60 });
dataset[1].value = 30;
refresh();
}, 500);
}
</script>
</head>
<body>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment