Skip to content

Instantly share code, notes, and snippets.

@romsson
Last active January 17, 2020 15:01
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/653eaaf6f6b5655af0ebb1e67d3be986 to your computer and use it in GitHub Desktop.
Save romsson/653eaaf6f6b5655af0ebb1e67d3be986 to your computer and use it in GitHub Desktop.
line chart (temporal data)
license: mit
[{"id" : 1, "name": "A", "value": 10, "date": "2016-01"},
{"id" : 2, "name": "B", "value": 30, "date": "2016-02"},
{"id" : 3, "name": "C", "value": 20, "date": "2016-03"} ,
{"id" : 3, "name": "C", "value": 20, "date": "2016-04"} ]
<!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; }
</style>
</head>
<body>
<script>
// Feel free to change or delete any of the code you see in this editor!
var margin = {top: 20, right: 10, bottom: 20, left: 10};
var width = 480 - margin.left - margin.right,
height = 250 - margin.top - margin.bottom;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
// var data = d3.range(10).map(Math.random)
d3.json("dataset.json", function(data) {
var parseDate = d3.timeParse("%Y-%m")
var displayDate = d3.timeFormat("%b %y")
data.forEach(function(d) {
d.value = +d.value;
d.date = parseDate(d.date);
});
var x = d3.scaleTime()
.domain(d3.extent(data, function(d) { return d.date; }))
.range([margin.left, width + margin.left])
var y = d3.scaleLinear()
.domain([d3.min(data, function(d) { return d.value; }),
d3.max(data, function(d) { return d.value; })])
.range([margin.top, height + margin.top])
var line = d3.line()
.curve(d3.curveMonotoneX)
.x(function(d, i) { return x(d.date); })
.y(function(d, i) { return height-y(d.value); })
svg.selectAll("path").data([data]).enter()
.append("path")
.style("fill", "none")
.style("stroke", "black")
.attr("d", line);
svg.selectAll("text").data(data).enter()
.append('text')
.attr("x", function(d, i) { return x(d.date); })
.attr("y", function(d, i) { return height; })
.text(function(d) { return displayDate(d.date)})
})
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment