Skip to content

Instantly share code, notes, and snippets.

@deristnochda
Created November 28, 2016 16:28
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 deristnochda/ef29cbb2724bf918971400797166120c to your computer and use it in GitHub Desktop.
Save deristnochda/ef29cbb2724bf918971400797166120c to your computer and use it in GitHub Desktop.
d3js v4 line chart (zoom not working)
<html>
<head>
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
.axis {
font-size: 11pt;
}
.line {
fill: none;
stroke: steelblue;
stroke-width: 2px;
}
</style>
</head>
<body>
<div class="container">
<svg></svg>
</div>
<script>
var data_str = "x,y\n0,0.45\n1,-0.55\n2,-0.15\n3,2.06\n4,1.49\n5,2.34\n6,3.21\n7,4.56\n8,3.78\n9,4.24\n10,5.01"
var data = d3.csvParse(data_str, function(d) {
return {
x:+d.x,
y:+d.y,
};
});
var margin = {top: 20, right: 50, bottom: 20, left: 80},
width = 900 - margin.left - margin.right,
height = 450 - margin.top - margin.bottom;
var zoom = d3.zoom()
.scaleExtent([1, 5])
.extent([100, 100], [width-100, height-100])
.on("zoom", zoomed);
function zoomed() {
svg.selectAll(".charts")
.attr("transform", d3.event.transform);
d3.selectAll('.line').style("stroke-width", 2/d3.event.transform.k);
gX.call(xAxis.scale(d3.event.transform.rescaleX(x)));
gY.call(yAxis.scale(d3.event.transform.rescaleY(y)));
}
var svg = d3.select("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.call(zoom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var x = d3.scaleLinear()
.domain([0, 10])
.range([0, width]);
var y = d3.scaleLinear()
.domain([-2, 6])
.range([height, 0]);
var xAxis = d3.axisBottom(x);
var yAxis = d3.axisLeft(y);
var gX = svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
var gY = svg.append("g")
.attr("class", "axis axis--y")
.call(yAxis)
line = d3.line()
.x(function(d) { return x(d.x); })
.y(function(d) { return y(d.y); });
svg.append("g")
.attr("class", "charts")
.append("path")
.datum(data)
.attr("class", "line")
.attr("d", function(d) { return line(d); });
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment