Skip to content

Instantly share code, notes, and snippets.

@flintobrien
Last active August 29, 2015 13:57
Show Gist options
  • Save flintobrien/9744945 to your computer and use it in GitHub Desktop.
Save flintobrien/9744945 to your computer and use it in GitHub Desktop.
d3-traits Pan & Zoom via Brush

This example demonstrates how to use d3.trait.control.brush trait. Click and drag on the bottom chart to pan & zoom the top chart. The data is from the original D3.js example, Focus+Context via Brushing

Note that the botom and top charts can be different chart types. The only requirement is that the source and target axes have similar data.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
font: 10px sans-serif;
}
.brush .extent {
stroke: white;
stroke-width: 2;
fill-opacity: .25;
shape-rendering: crispEdges;
}
</style>
<link rel="stylesheet" href="http://gec.github.io/Total-Grid/d3-traits.css"/>
<body>
<div id="chart" style="height: 400px; width: 960px;"></div>
<div id="brush-chart" style="height: 88px; width: 960px; margin-top: 10px;"></div>
<script src="http://d3js.org/d3.v3.js"></script>
<script src="http://gec.github.io/Total-Grid/d3-traits.min.js"></script>
<script>
var parseDate = d3.time.format("%b %Y").parse,
chartEl = d3.select('#chart'),
brushChartEl = d3.select('#brush-chart')
var config = {
x1: function(d) { return d.date; },
y1: function(d) { return d.price; },
margin: {top: 25, right: 20}
}
var chart = d3.trait( d3.trait.chart.base, config)
.trait( d3.trait.scale.time, { axis: "x1" })
.trait( d3.trait.scale.linear, { axis: "y1", domainMin: 0 })
.trait( d3.trait.chart.area, { })
.trait( d3.trait.axis.time.month, { axis: "x1"})
.trait( d3.trait.axis.linear, { axis: "y1"})
config.margin.top = 10
var brushChart = d3.trait( d3.trait.chart.base, config)
.trait( d3.trait.scale.time, { axis: "x1" })
.trait( d3.trait.scale.linear, { axis: "y1", domainMin: 0 })
.trait( d3.trait.chart.area, { })
// The brush trait targets the selection of the top chart.
.trait( d3.trait.control.brush, { axis: 'x1', target: chart, targetAxis: 'x1'})
.trait( d3.trait.axis.time.month, { axis: "x1"})
.trait( d3.trait.axis.linear, { axis: "y1", extentTicks: true })
d3.csv("/mbostock/raw/1667367/sp500.csv", function(error, data) {
data.forEach(function(d) {
d.date = parseDate(d.date);
d.price = +d.price;
});
var series = [ data]
var selection = chartEl.datum( series)
chart.call( selection)
selection = brushChartEl.datum( series)
brushChart.call( selection)
});
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment