Skip to content

Instantly share code, notes, and snippets.

@romsson
Last active October 19, 2017 12:50
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/25eb258c0da9e3c72d1659513efb078e to your computer and use it in GitHub Desktop.
Save romsson/25eb258c0da9e3c72d1659513efb078e to your computer and use it in GitHub Desktop.
simple line chart (d3.v4)
license: mit
[{"name": "A", "value": 10, "date": "2016-01"},
{"name": "B", "value": 30, "date": "2016-02"},
{"name": "C", "value": 20, "date": "2016-03"},
{"name": "D", "value": 40, "date": "2016-04"},
{"name": "E", "value": 50, "date": "2016-05"},
{"name": "F", "value": 20, "date": "2016-06"},
{"name": "G", "value": 10, "date": "2016-07"}
]
<!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!
var svg = d3.select("body").append("svg")
.attr("width", 960)
.attr("height", 500)
var width = 800;
var height = 400;
var x = d3.scaleLinear()
.range([0, width]);
var y = d3.scaleLinear()
.range([0, height]);
var line = d3.line()
.curve(d3.curveLinear)
.x(function(d, i) { return x(i); })
.y(function(d) { return y(d); });
var color = d3.scaleOrdinal(d3.schemeCategory20);
var g = svg.append("g")
.attr("transform", "translate(50, 0)")
data = [];
d3.range(10).map(function(d) {
var v = [];
d3.range(100).map(function(e) { v.push(d * Math.random()); });
data.push(v);
})
x.domain([0, data[0].length]);
y.domain([
d3.min(data, function(d) { return d3.min(d, function(e) { return e; }); }),
d3.max(data, function(d) { return d3.max(d, function(e) { return e; }); })
]);
var lines = g.selectAll(".line").data(data)
.enter()
.append("g")
.attr("class", "line");
lines.append("path")
.attr("class", "line")
.attr("d", function(d) {console.log(line(d)); return line(d); })
.style("stroke", function(d, i) { return color(i); });
g.selectAll("path").data(data).enter().append("path")
.attr("class", "line")
.attr("d", function(d) { console.log(d); return line(d); });
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment