Skip to content

Instantly share code, notes, and snippets.

@git-ashish git-ashish/README forked from rmarimon/README
Created Sep 24, 2013

Embed
What would you like to do?
Click on the x axis line and drag to change the scale of the graph.
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>bar</title>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js"></script>
<style type="text/css">
#chart {
font-size: 12px;
}
#chart line.data {
stroke: steelblue;
stroke-width: 6px;
}
#chart .xaxis {
stroke: black;
stroke-width: 6px;
}
</style>
</head>
<body>
<div id="chart"></div>
<script type="text/javascript">
var w = 960,
h = 320,
m = [ 15, 5, 15, 5 ], // top, right, bottom, left (ala css)
mw = w - m[1] - m[3],
mh = h - m[0] - m[2],
data = [ { x: 1, y: 10 }, { x: 3, y: 12 }, { x: 4, y: 14 }, { x: 9, y: 16 } ];
var x = d3.scale.linear()
.domain([d3.min(data, function(d) { return d.x; }), d3.max(data, function(d) { return d.x; })])
.range([0, mw]),
y = d3.scale.linear()
.domain([Math.min(0, d3.min(data, function(d) { return d.y; })), d3.max(data, function(d) { return d.y; })])
.range([0, mh]);
var vis = d3.select("#chart")
.append("svg:svg")
.attr("width", w)
.attr("height", h)
.attr("pointer-events", "all")
.append("svg:g")
.attr("transform", "translate(" + m[3] + "," + m[0] + ")");
draw();
function draw() {
var lines = vis.selectAll("line.data")
.data(data);
lines.exit().remove();
lines.enter()
.append("svg:line")
.attr("class", "data");
lines
.attr("x1", function(d) { return x(d.x); })
.attr("x2", function(d) { return x(d.x); })
.attr("y1", function(d) { return mh - y(0); })
.attr("y2", function(d) { return mh - y(d.y); });
}
// drag x-axis logic
var downx = Math.NaN;
var downscalex;
// attach the mousedown to the line
vis.append("svg:line")
.attr("class", "xaxis")
.attr("x1", 0)
.attr("x2", mw)
.attr("y1", mh - y(0))
.attr("y2", mh - y(0))
.on("mousedown", function(d) {
var p = d3.svg.mouse(vis[0][0]);
downx = x.invert(p[0]);
downscalex = x;
});
// attach the mousemove and mouseup to the body
// in case one wonders off the axis line
d3.select('body')
.on("mousemove", function(d) {
if (!isNaN(downx)) {
var p = d3.svg.mouse(vis[0][0]), rupx = p[0];
if (rupx != 0) {
x.domain([downscalex.domain()[0], mw * (downx - downscalex.domain()[0]) / rupx + downscalex.domain()[0]]);
}
draw();
}
})
.on("mouseup", function(d) {
downx = Math.NaN;
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.