Skip to content

Instantly share code, notes, and snippets.

@rjschie
Last active April 7, 2016 05:20
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 rjschie/e7bf1dd1db64c9582d3ae6d6f5f2355e to your computer and use it in GitHub Desktop.
Save rjschie/e7bf1dd1db64c9582d3ae6d6f5f2355e to your computer and use it in GitHub Desktop.
D3 Line Chart that scales
<!DOCTYPE html>
<html>
<meta name="description" content="D3 Line chart that scales">
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
<style>
svg {
border: 1px solid red;
}
svg path {
stroke: black;
stroke-width: 3px;
fill: none;
}
svg circle {
fill: white;
stroke: black;
stroke-width: 2px;
}
</style>
<script>
var lineOrig = [5,8,20,12,40,18,8,38,12,21,12,9,16,7,3,1,1, 0];
var lineData = lineOrig.reduce(function(arr, curr) {
let v = curr + arr[arr.length - 1] || curr;
arr.push(v);
return arr;
}, []);
var svgWidth = 200;
var svgHeight = 200;
var x = d3.scale.linear()
.domain([0, lineData.length-1])
.range([0, svgWidth]);
var y = d3.scale.linear()
.domain([0, d3.max(lineData)])
.range([svgHeight, 0]);
var line = d3.svg.line()
.x(function(d,i) {
return x(i);
})
.y(function(d) {
return y(d);
})
.interpolate('cardinal');
var svg = d3.select('body')
.append('svg')
.attr('width', svgWidth)
.attr('height', svgHeight);
//Line
svg.append('path')
.attr('d', line(lineData));
//Points
svg.selectAll('circle')
.data(lineData)
.enter()
.append('circle')
.attr('cx', function(d,i) {
return x(i) - 1;
})
.attr('cy', function(d) {
return y(d);
});
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment