Skip to content

Instantly share code, notes, and snippets.

@zzolo
Created November 16, 2015 22:13
Show Gist options
  • Save zzolo/e07e8f964b334a60201d to your computer and use it in GitHub Desktop.
Save zzolo/e07e8f964b334a60201d 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,58.3],[12,74.6],[98,70.8],[3.2,26.2],[94.9,51],[4.6,22.8],[77.2,64.3],[28.1,20.2],[12.4,58.3],[20.2,47.4],[35.6,58.8],[23,48.7],[76.5,68.4],[10,7.4],[73.6,62.8],[47.2,78.7],[62.5,50],[12.5,51.2],[75.3,52.3],[30.3,59.8],[5,78.8],[7.3,77],[12.1,32.6],[10.1,87.8],[22.8,61.4],[16.4,79],[95.7,17.2],[26.2,81.7],[81.8,85.2],[36.3,59.9],[12.2,49.2],[22.4,66.2],[4.5,68.3],[84.5,29.5],[94.1,70.2],[56.9,43.8],[28.7,63.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