Skip to content

Instantly share code, notes, and snippets.

@emeeks
Last active March 17, 2016 02:25
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 emeeks/0c6c30853cfd29e5c2bd to your computer and use it in GitHub Desktop.
Save emeeks/0c6c30853cfd29e5c2bd to your computer and use it in GitHub Desktop.
Ch. 11, Fig. 12 - D3.js in Action

This is the code for Chapter 11, Figure 12 from D3.js in Action demonstrating d3.svg.brush() XY-brushing as well as a simple selection of elements that fall within the region brushed.

<html>
<head>
<title>D3 in Action Chapter 11 - Example 7</title>
<meta charset="utf-8" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
</head>
<style>
body, html {
margin: 0;
}
canvas {
position: absolute;
width: 500px;
height: 500px;
}
svg {
position: absolute;
width:500px;
height:500px;
}
path.country {
fill: gray;
stroke-width: 1;
stroke: black;
opacity: .5;
}
path.sample {
stroke: black;
stroke-width: 1px;
fill: red;
fill-opacity: .5;
}
line.link {
stroke-width: 1px;
stroke: black;
stroke-opacity: .5;
}
circle.node {
fill: red;
stroke: white;
stroke-width: 1px;
}
circle.xy {
fill: pink;
stroke: black;
stroke-width: 1px;
}
rect.extent {
fill-opacity:.1;
stroke: black;
stroke-width: 1px;
}
</style>
<body>
<canvas height="500" width="500"></canvas>
<div id="viz">
<svg></svg>
</div>
</body>
<footer>
<script>
sampleData = d3.range(3000).map(function(d) {
var datapoint = {};
datapoint.id = "Sample Node " + d;
datapoint.x = Math.random() * 500;
datapoint.y = Math.random() * 500;
return datapoint;
})
d3.select("svg").selectAll("circle").data(sampleData)
.enter()
.append("circle")
.attr("r", 3)
.attr("cx", function(d) {return d.x})
.attr("cy", function(d) {return d.y})
.style("fill", "pink")
.style("stroke", "black")
.style("stroke-width", "1px")
var brush = d3.svg.brush()
.x(d3.scale.identity().domain([0, 500]))
.y(d3.scale.identity().domain([0, 500]))
.on("brush", brushed);
d3.select("svg").call(brush);
function brushed() {
var e = brush.extent();
d3.selectAll("circle")
.style("fill", function (d) {
if (d.x >= e[0][0] && d.x <= e[1][0] && d.y >= e[0][1] && d.y <= e[1][1]) {
return "darkred";
}
else {
return "pink";
}
})
}
</script>
</footer>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment