Created
September 10, 2012 14:51
-
-
Save raffazizzi/3691274 to your computer and use it in GitHub Desktop.
testing d3.js brush
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<style> | |
.brush .extent { | |
stroke: gray; | |
fill: blue; | |
fill-opacity: .165; | |
} | |
</style> | |
<body> | |
<script type="text/javascript" src="http://d3js.org/d3.v2.js"></script> | |
<script> | |
var data = new Array(200); | |
for (i=0; i<data.length; i++) data[i] = Math.random() > 0.5 ? "Orange" : "Cyan"; | |
var width = 800, | |
height = 300; | |
var svg = d3.select("body").append("svg:svg") | |
.attr("width", width) | |
.attr("height", height); | |
bar = function(range) { | |
var x_range = d3.scale.linear() | |
.domain([0, range.length]) | |
.range([0, width]); | |
svg.selectAll("rect.items").remove(); | |
svg.selectAll("rect.items") | |
.data(range) | |
.enter().append("svg:rect") | |
.attr("class", "items") | |
.attr("x", function(d, i) {return x_range(i);}) | |
.attr("y", 0) | |
.attr("width", width/range.length-2) | |
.attr("height", 100) | |
.attr("fill", function(d) {return d}) | |
.attr("title", function(d) {return d}); | |
} | |
var start = 21; | |
bar(data.slice(0, start), true); | |
var control_x_range = d3.scale.linear() | |
.domain([0, data.length]) | |
.range([0, width]); | |
controlBar = svg.selectAll("rect.itemsControl") | |
.data(data) | |
.enter().append("svg:rect") | |
.attr("class", "itemsControl") | |
.attr("x", function(d, i) {return control_x_range(i);}) | |
.attr("y", 110) | |
.attr("width", width/data.length-2) | |
.attr("height", 20) | |
.attr("fill", function(d) {return d}); | |
svg.append("g") | |
.attr("class", "brush") | |
.call(d3.svg.brush().x(d3.scale.linear().range([0, width])) | |
.extent([0,1*start/data.length]) | |
.on("brush", brush)) | |
.selectAll("rect") | |
.attr("y", 110) | |
.attr("height", 20); | |
function brush() { | |
var s = d3.event.target.extent(); | |
if (s[1]-s[0] < 0.5) { | |
var start = Math.round((data.length-1)*s[0]); | |
var end = Math.round((data.length-1)*s[1]); | |
bar(data.slice(start,end)); | |
} | |
else {d3.event.target.extent([s[0],s[0]+0.5]); d3.event.target(d3.select(this));} | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment