Skip to content

Instantly share code, notes, and snippets.

@jgoodall
Last active December 22, 2015 22:28
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 jgoodall/6539788 to your computer and use it in GitHub Desktop.
Save jgoodall/6539788 to your computer and use it in GitHub Desktop.
intro to d3: scatterplot using scales and axes
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.circle {
fill: steelblue;
stroke: '#fff';
}
.label {
fill: #777;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var width = 400
, height = 400
, margin = {top: 25, right: 50, bottom: 40, left: 50}
// first number will be plotted on the x axis
// second number will be plotted on the y axis
// third number will be used as the radius
var dataset = [
[ 5, 20, 12],
[ 480, 90, 11],
[ 250, 50, 13],
[ 100, 33, 11],
[ 330, 95, 17],
[ 410, 12, 15],
[ 475, 44, 13],
[ 25, 67, 11],
[ 600, 81, 12],
[ 85, 21, 11],
[ 120, 39, 12],
[ 220, 88, 16]
];
// set up the scales
var xScale = d3.scale.linear()
.range([0, width])
.domain([0, d3.max(dataset, function(d) { return d[0]; })])
.nice();
var yScale = d3.scale.linear()
.range([height, 0])
.domain([0, d3.max(dataset, function(d) { return d[1]; })])
.nice();
// set the axes
var xAxis = d3.svg.axis()
.scale(xScale)
.orient('bottom')
.outerTickSize(1);
var yAxis = d3.svg.axis()
.scale(yScale)
.orient('left')
.outerTickSize(1);
// append the svg to the body of the page and set the width and height
// append a 'g' element to group the circles together and 'translate'
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// bind the data and set the x, y, and radius of each point
var dot = svg.selectAll("circle")
.data(dataset)
.enter().append("circle")
.attr({
"class": "circle"
, "cx": function(d) { return xScale(d[0]); }
, "cy": function(d) { return yScale(d[1]); }
, "r": function(d) { return d[2] / 2; }
});
// draw the axes
var svgXaxis = svg.append('g')
.attr({
'class': 'axis label'
, 'transform': 'translate(0,' + height + ')'
})
.call(xAxis);
svgXaxis.append('text')
.attr({
'class': 'label'
, 'x': width / 2
, 'y': margin.bottom - 4
, 'text-anchor': 'middle'
})
.text('first set of numbers');
// draw Y axis
var svgYaxis = svg.append('g')
.attr({
'class': 'axis label'
})
.call(yAxis);
svgYaxis.append('text')
.attr({
'class': 'label'
, 'transform': 'translate(-290,320)rotate(-90)'
, 'x': margin.left
, 'y': height / 2
, 'text-anchor': 'middle'
})
.text('more numbers');
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment