Skip to content

Instantly share code, notes, and snippets.

@romsson
Last active May 16, 2018 04:29
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 romsson/d9faa97f6b0cc00053b7636e757b135b to your computer and use it in GitHub Desktop.
Save romsson/d9faa97f6b0cc00053b7636e757b135b to your computer and use it in GitHub Desktop.
[introd3] line chart
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
.line {
fill: none;
stroke: black;
stroke-width: 1.5px;
}
</style>
</head>
<body>
<script>
// Feel free to change or delete any of the code you see in this editor!
// Margin setup
var margin = {top: 20, right: 30, bottom: 20, left: 100},
width = 760 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom;
var data = d3.range(10).map(function(d, i) {
return {x: i, y: Math.random()* 100}
})
// Basic SVG canvas
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 + ")");
// Linear scale
var x = d3.scaleLinear()
.domain([0, 10])
.range([0, width]);
// Linear scale
var y = d3.scaleLinear()
.domain([0, 100])
.range([height, height - 200]);
var line = d3.line().curve(d3.curveCardinal)
.x(function(d) { return x(d.x); })
.y(function(d) { return y(d.y); });
svg.selectAll(".line").data([data]).enter()
.append("path")
.attr("class", "line")
.attr("d", line);
svg.selectAll(".circle").data(data).enter()
.append("circle")
.attr("cx", function(d) { return x(d.x); })
.attr("cy", function(d) { return y(d.y); })
.attr("class", "line")
.attr("r", 10);
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment