Skip to content

Instantly share code, notes, and snippets.

@zzolo
Last active November 16, 2015 21:55
Show Gist options
  • Save zzolo/80097d54d4ec4ce83222 to your computer and use it in GitHub Desktop.
Save zzolo/80097d54d4ec4ce83222 to your computer and use it in GitHub Desktop.
A scatter plot
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
svg { width: 100%; height: 100%; }
</style>
</head>
<body>
<script>
var data = [[83,62.5],[12,76.6],[98,79.2],[3.2,38],[94.9,54.9],[4.6,27.7],[77.2,69.7],[28.1,27.4],[12.4,70.8],[20.2,77.6],[35.6,76.5],[23,52.5],[76.5,76.3],[10,14.9],[73.6,67.4],[47.2,87.2],[62.5,68.8],[12.5,55.5],[75.3,55.3],[30.3,62.7],[5,81.1],[7.3,79.2],[12.1,41.3],[10.1,92],[22.8,65.3],[16.4,84.4],[95.7,27.8],[26.2,85.7],[81.8,92.6],[36.3,62.6],[12.2,59.3],[22.4,69.3],[4.5,72.2],[84.5,32.5],[94.1,76.5],[56.9,49.4],[28.7,69.8]];
var margin = {top: 20, right: 15, bottom: 60, left: 60}
, width = 960 - margin.left - margin.right
, height = 500 - margin.top - margin.bottom;
var x = d3.scale.linear()
.domain([0, d3.max(data, function(d) { return d[0]; })])
.range([ 0, width ]);
var y = d3.scale.linear()
.domain([0, d3.max(data, function(d) { return d[1]; })])
.range([ height, 0 ]);
var chart = d3.select('body')
.append('svg:svg')
.attr('width', width + margin.right + margin.left)
.attr('height', height + margin.top + margin.bottom)
.attr('class', 'chart')
var main = chart.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')
.attr('width', width)
.attr('height', height)
.attr('class', 'main')
// draw the x axis
var xAxis = d3.svg.axis()
.scale(x)
.orient('bottom');
main.append('g')
.attr('transform', 'translate(0,' + height + ')')
.attr('class', 'main axis date')
.call(xAxis);
// draw the y axis
var yAxis = d3.svg.axis()
.scale(y)
.orient('left');
main.append('g')
.attr('transform', 'translate(0,0)')
.attr('class', 'main axis date')
.call(yAxis);
var g = main.append("svg:g");
g.selectAll("scatter-dots")
.data(data)
.enter().append("svg:circle")
.attr("cx", function (d,i) { return x(d[0]); } )
.attr("cy", function (d) { return y(d[1]); } )
.attr("r", 8);
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment