block by mbostock 3cfa2d1dbae2162a60203b287431382c

Sleep Cycles

Full Screen

This example shows how to plot daily time intervals in the style of Eric Boam’s Seven Months of Sleep. (The data here is fake.)

This graph uses a time scale to plot time-of-day along the y-axis. Time scales are normally used to plot absolute time: a specific moment on a specific day in a specific year. Here, though, we’re interested in studying the daily pattern, so the start and end times for each sleep interval are converted to offsets (elapsed times) relative to the midnight immediately preceeding the start time. Given an interval d:

var midnight = d3.utcDay.floor(d[0]),
    startOffset = d[0] - midnight,
    endOffset = d[1] - midnight;

The offsets are measured in milliseconds since that’s the JavaScript convention. To avoid inconsistencies across browser local time zones, the dates are represented as local times in the data but parsed as UTC. The resulting Date objects are inconsistent with the original dates, but the difference is irrelevant because we just want to plot the local time-of-day.

Also, this representation makes it easy to convert an offset back to an absolute time on an arbitrary day for using with a d3.scaleUtc and d3.utcFormat. The arbitrary day is the UNIX epoch:

function date(offset) {
  return new Date(offset);
}

A similar technique is used in my visualization of Eric Fischer’s Twitter feed.

index.html

generate-fake-data

sleep.csv