Skip to content

Instantly share code, notes, and snippets.

@EfratVil EfratVil/README.md
Last active Sep 16, 2017

Embed
What would you like to do?
Fixed size slider

Line chart with fixed size slider. Slider can only be moved from side to side.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
.line {
fill: none;
stroke: steelblue;
stroke-width: 1.5px;
}
/*.handle {
pointer-events: none;
}*/
</style>
<head>
</head>
<body>
<script src="//d3js.org/d3.v4.min.js"></script>
<script>
function randomData(samples) {
var data = [],
random = d3.randomNormal();
for (i = 0; i < samples; i++) {
data.push({
id: i + 1,
y: d3.format(".3")(random())
});
}
return data;
}
var data = randomData(200);
var margin = {top: 20, right: 20, bottom: 30, left: 50},
width = 560 - margin.left - margin.right,
height = 260 - margin.top - margin.bottom;
var x = d3.scaleLinear()
.range([0, width]);
var y = d3.scaleLinear()
.range([height, 0]);
var line = d3.line()
.x(function(d) { return x(d.id); })
.y(function (d) { return y(d.y); });
var brush = d3.brushX()
.extent([[0, 0], [width, height]]);
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 + ")");
data.forEach(function (d) {
Object.keys(data[0]).forEach(function (k) {
d[k] = +d[k];
});
});
x.domain(d3.extent(data, function(d) { return d.id; }));
y.domain(d3.extent(data, function (d) { return d.y; }));
var gX = svg.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
var gY = svg.append("g")
.attr("class", "axis axis--y")
.call(d3.axisLeft(y));
svg.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line);
var gBrush = svg.append("g")
.attr("class", "brush")
.call(brush)
.call(brush.move, [x(60), x(120)]);
// removes handle to resize the brush
d3.selectAll('.brush>.handle').remove();
// removes crosshair cursor
d3.selectAll('.brush>.overlay').remove();
</script>
</body>
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.