Skip to content

Instantly share code, notes, and snippets.

@lmullen
Last active August 29, 2015 13:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lmullen/9590989 to your computer and use it in GitHub Desktop.
Save lmullen/9590989 to your computer and use it in GitHub Desktop.
Reusable Scatter Plot Function

Learning to create a reusable chart function for a scatter plot, following Mike Bostock's "Towards Reusable Charts." Also includes a random data generator.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<style>
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
#viz1 .points circle {
fill: steelblue;
fill-opacity: 0.6;
stroke: black;
}
#viz2 .points circle {
fill: orange;
fill-opacity: 0.6;
stroke: black;
}
</style>
</head>
<body>
<div id="viz1"></div>
<div id="viz2"></div>
<script src="visualization.js"></script>
</body>
</html>
function randomData(numPoints) {
var data = [];
random = function() {return Math.floor(Math.random() * 100);};
for (i = 0; i < numPoints; i++) {
data.push({
x: random(),
y: random(),
z: random()
});
}
return data;
}
function scatterPlot() {
var margin = {top: 10, right: 25, bottom: 25, left: 40},
width = 600,
height = 400,
xValue = function(d) { return d[0]; },
yValue = function(d) { return d[1]; },
sizeValue = function(d) { return d[2]; },
xScale = d3.scale.linear(),
yScale = d3.scale.linear(),
sizeScale = d3.scale.sqrt(),
xAxis = d3.svg.axis().scale(xScale).orient("bottom").tickSize(6,1);
yAxis = d3.svg.axis().scale(yScale).orient("left").tickSize(6, 1);
function chart(selection) {
selection.each(function(data) {
// Convert data to standard representation greedily;
// this is needed for nondeterministic accessors.
data = data.map(function(d, i) {
return [xValue.call(data, d, i),
yValue.call(data, d, i),
sizeValue.call(data, d, i)];
});
// Update the x-scale.
xScale
.domain(d3.extent(data, function(d) { return d[0]; }))
.range([0, width - margin.left - margin.right]);
// Update the y-scale.
yScale
.domain([0, d3.max(data, function(d) { return d[1]; })])
.range([height - margin.top - margin.bottom, 0]);
// Update the size-scale.
sizeScale
.domain([d3.min(data, function(d) { return d[2]; }),
d3.max(data, function(d) { return d[2]; })])
.range([2,8]);
// Select the svg element, if it exists.
var svg = d3.select(this).selectAll("svg").data([data]);
// Otherwise, create the skeletal chart.
var gEnter = svg.enter().append("svg").append("g");
gEnter.append("g").attr("class", "points");
gEnter.append("g").attr("class", "x axis");
gEnter.append("g").attr("class", "y axis");
// Update the outer dimensions.
svg .attr("width", width)
.attr("height", height);
// Update the inner dimensions.
var g = svg.select("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Update the points
g.select("g.points")
.selectAll("circles.point")
.data(data)
.enter()
.append("circle")
.attr("class", "point")
.attr("r", function(d) { return sizeScale(d[2]); })
.attr("transform", function(d) {
return "translate(" + xScale(d[0]) + "," + yScale(d[1]) + ")";
});
// Update the x-axis.
g.select(".x.axis")
.attr("transform", "translate(0," + yScale.range()[0] + ")")
.call(xAxis);
// Update the y-axis.
g.select(".y.axis")
.attr("transform", "translate(0," + xScale.range()[0] + ")")
.call(yAxis);
});
}
// The x-accessor for the path generator; xScale ∘ xValue.
function X(d) {
return xScale(d[0]);
}
// The x-accessor for the path generator; yScale ∘ yValue.
function Y(d) {
return yScale(d[1]);
}
function size(d) {
return sizeScale(d[2]);
}
chart.margin = function(_) {
if (!arguments.length) return margin;
margin = _;
return chart;
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
chart.x = function(_) {
if (!arguments.length) return xValue;
xValue = _;
return chart;
};
chart.y = function(_) {
if (!arguments.length) return yValue;
yValue = _;
return chart;
};
chart.size = function(_) {
if (!arguments.length) return sizeValue;
sizeValue = _;
return chart;
};
return chart;
}
var chart = scatterPlot()
.x( function(d) { return +d.x; } )
.y( function(d) { return +d.y; } )
.size( function(d) { return +d.z; } )
.height(250);
// Bind the data to the chart to the #viz elements
chart1 = d3.select('#viz1').datum(randomData(50)).call(chart);
chart2 = d3.select('#viz2').datum(randomData(50)).call(chart);
@Hypercubed
Copy link

Line #24 should end in a comma, this causes yAxis to be declared globally.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment