Skip to content

Instantly share code, notes, and snippets.

@quantbo
Last active December 13, 2016 23:56
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 quantbo/cde60e268f21ff0017a5e380cbde37bd to your computer and use it in GitHub Desktop.
Save quantbo/cde60e268f21ff0017a5e380cbde37bd to your computer and use it in GitHub Desktop.
D3 time series: gap not appearing
date value
1999-03-01 1.0891
1999-03-02 1.0931
1999-03-03 1.0888
1999-03-04 1.0824
1999-03-05 1.0843
1999-03-08 1.0899
1999-03-09 1.0873
1999-03-10 1.0961
1999-03-11 1.0932
1999-03-12 1.0936
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
.line {
fill: none;
stroke: red;
stroke-width: 2px;
}
</style>
</head>
<body>
<svg></svg>
</body>
<script src='index.js'></script>
</html>
'use strict';
const height = 400, width = 800;
const margin = {top: 10, right: 10, bottom: 40, left: 20};
const innerHeight = height - margin.bottom - margin.top;
const innerWidth = width - margin.left - margin.right;
//Parse date function. dates are in the format 1999-01-01 (year-month-day).
const parsedate = d3.timeParse('%Y-%m-%d');
//Set ranges.
const xScale = d3.scaleTime().range([0, innerWidth]);
const yScale = d3.scaleLinear().range([innerHeight, 0]);
//Graph generator.
const grph = d3.line()
.defined(function(d) { return !isNaN(d.value); })
.x((d) => {return xScale(d.date);})
.y((d) => {return yScale(d.value);});
//Set up svg and g els.
const svg = d3.select('svg')
.attr('height', height)
.attr('width', width);
const g_el = svg.append('g')
.attr('height', innerHeight)
.attr('width', innerWidth)
.attr('transform', `translate(${margin.left}, ${margin.top})`);
//Load and graph the data.
d3.csv('gap.csv', (error, data) => {
if (error) throw new Error('d3.csv error');
//Transform data from strings to dates and numbers.
data.forEach((d) => {
d.date = parsedate(d.date);
d.value = +d.value;
})
//Set scale domains.
xScale.domain(d3.extent(data, (d) => {return d.date;}));
yScale.domain(d3.extent(data, (d) => {return d.value;}));
//Generate graph.
g_el.append('path')
.data([data])
.attr('class', 'line')
.attr('d', grph);
//Place circles where the data points are.
g_el.selectAll('wombat') //Any non-empty string will serve here.
.data(data)
.enter()
.append('circle')
.attr('r', 5)
.attr('cx', (d) => {return xScale(d.date);})
.attr('cy', (d) => {return yScale(d.value);})
.attr('fill', 'black');
//x axis.
g_el.append('g')
.attr('transform', `translate(0, ${innerHeight})`)
.call(d3.axisBottom(xScale));
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment