Skip to content

Instantly share code, notes, and snippets.

@mtandre
Last active September 30, 2017 19:07
Show Gist options
  • Save mtandre/270bdf0c5658e683cb79460c2cdebe78 to your computer and use it in GitHub Desktop.
Save mtandre/270bdf0c5658e683cb79460c2cdebe78 to your computer and use it in GitHub Desktop.
polka dots
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>scatter plot 2</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style type="text/css">
text { font-family:monospace; font-size:11px; }
</style>
</head>
<body>
<svg></svg>
<br><button>polka dots</button>
<script>
var w = 800,
h = 400,
padding = 30;
var dataset = [];
var maxRange = Math.random() * 1000;
for (var i = 0; i < 200; i++) {
dataset.push([
Math.floor(Math.random() * maxRange),
Math.floor(Math.random() * maxRange)
]);
}
var xScale = d3.scaleLinear()
.domain([0, d3.max(dataset, function(d) { return d[0]; })])
.range([padding, w - padding * 2]);
var yScale = d3.scaleLinear()
.domain([0, d3.max(dataset, function(d) { return d[1]; })])
.range([h - padding, padding]);
var xAxis = d3.axisBottom()
.scale(xScale)
.ticks(5);
var yAxis = d3.axisLeft()
.scale(yScale)
.ticks(5);
var svg = d3.select('svg')
.attr('width', w)
.attr('height', h);
svg.append('clipPath')
.attr('id', 'chart-area')
.append('rect')
.attr('x', padding)
.attr('y', padding)
.attr('width', w - padding * 3)
.attr('height', h - padding * 2);
svg.append('g')
.attr('id', 'circles')
.attr('clip-path', 'url(#chart-area)')
.selectAll('circle')
.data(dataset)
.enter()
.append('circle')
.attr('cx', function(d) {
return xScale(d[0]);
})
.attr('cy', function(d) {
return yScale(d[1]);
})
.attr('r', 4);
svg.append('g')
.attr('class', 'x axis')
.attr('transform', 'translate(0,' + (h - padding) + ')')
.call(xAxis);
svg.append('g')
.attr('class', 'y axis')
.attr('transform', 'translate(' + padding + ',0)')
.call(yAxis);
d3.select('button')
.on('click', function() {
var polka = function(d, i) {
d3.select(this)
.transition()
.delay(i * 5)
.duration(700)
.ease(d3.easeLinear)
.attr('fill', d3.schemeCategory20[Math.round(Math.random() * 20)]);
}
var dots = svg.select('#circles')
.selectAll('circle');
dots.filter(function(d){
return d[0] > xScale.domain()[0] + 4
&& d[0] < xScale.domain()[1] - 4
&& d[1] > yScale.domain()[0] + 4
&& d[1] < yScale.domain()[1] - 4;
}).each(polka);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment