Skip to content

Instantly share code, notes, and snippets.

@jasondavies
Created February 20, 2012 22:14
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 jasondavies/1871853 to your computer and use it in GitHub Desktop.
Save jasondavies/1871853 to your computer and use it in GitHub Desktop.
Zoom + Pan with Log Axes
<!DOCTYPE html>
<meta charset="utf-8">
<title>Zoom + Pan</title>
<style>
svg {
font: 10px sans-serif;
}
rect {
fill: #ddd;
}
circle {
fill-opacity: .5;
fill: #f00;
}
.axis path, .axis line {
fill: none;
stroke: #fff;
shape-rendering: crispEdges;
}
</style>
<body>
<script src="http://mbostock.github.com/d3/d3.v2.min.js?2.8.0"></script>
<script>
var margin = {top: 0, right: 0, bottom: 12, left: 36},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.log()
.domain([1, 100])
.range([0, width]);
var y = d3.scale.log()
.domain([1, 100])
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickSize(-height);
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(5)
.tickSize(-width);
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 + ")")
.style("pointer-events", "all")
.call(d3.behavior.zoom().x(x).y(y).scaleExtent([1, 8]).on("zoom", zoom));
svg.append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("width", width)
.attr("height", height);
svg.append("rect")
.attr("width", width)
.attr("height", height);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
svg.append("g").attr("clip-path", "url(#clip)")
.selectAll("circle")
.data(d3.range(1000).map(function() { return [1 + Math.random() * 99, 1 + Math.random() * 99]; }))
.enter().append("circle")
.attr("r", 4.5)
.attr("cx", function(d) { return x(d[0]); })
.attr("cy", function(d) { return y(d[1]); });
function zoom() {
svg.select(".x.axis").call(xAxis);
svg.select(".y.axis").call(yAxis);
svg.selectAll("circle")
.attr("cx", function(d) { return x(d[0]); })
.attr("cy", function(d) { return y(d[1]); });
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment