-
Notifications
You must be signed in to change notification settings - Fork 133
Visualizing Time Series Data
For time series data you'll typically want to use an XYFrame. (You can make Joy Plots with ORFrame but it's not as straightforward).
Suppose you have data in a format like this:
const data = [
{ id: 'linedata-1', color: '#00a2ce',
data: [
{ sales: 500, daysSinceRelease: 1 },
{ sales: 700, daysSinceRelease: 2 },
{ sales: 0, daysSinceRelease: 3 },
{ sales: 0, daysSinceRelease: 4 },
{ sales: 200, daysSinceRelease: 5 },
{ sales: 300, daysSinceRelease: 6 },
{ sales: 500, daysSinceRelease: 7 }
]
},
...etc..
]
If you pass this data to <XYFrame>
's lines
property and set the accessors to match the format of the data, it will render a line for each object in the data
array. XYFrame expects line data to be an object with an array of data in the object's coordinates
property, but our data has it in the data
property, so we have to update the lineDataAccessor to match that, too.
<XYFrame
lines={data}
xAccessor={"daysSinceRelease"}
yAccessor={"sales"}
lineDataAccessor={"data"}
lineStyle={d => ({ stroke: d.color, fill: d.color })}
/>
Now let's suppose instead of an integer value like daysSinceRelease
instead the data is formatted in a more typical manner, with dates, like the following:
const data = [
{ id: 'linedata-1', color: '#00a2ce',
data: [
{ sales: 500, timestamp: Date(2017, 7, 1) },
{ sales: 700, timestamp: Date(2017, 7, 2) },
{ sales: 0, timestamp: Date(2017, 7, 3) },
{ sales: 0, timestamp: Date(2017, 7, 4) },
{ sales: 200, timestamp: Date(2017, 7, 5) },
{ sales: 300, timestamp: Date(2017, 7, 6) },
{ sales: 500, timestamp: Date(2017, 7, 7) }
]
},
...etc..
]
If that's the case, you'll probably want to update the xScaleType
of the XYFrame to a scale built for time values.
import { scaleTime } from 'd3-scale'
<XYFrame
lines={data}
xAccessor={"timestamp"}
yAccessor={"sales"}
xScaleType={scaleTime()}
lineDataAccessor={"data"}
lineStyle={d => ({ stroke: d.color, fill: d.color })}
/>
If you want to add axes to your chart, just define some simple axes. The axis display is based on the orient
property of the axis object you send to XYFrame. Here's a nice pair of axes for the previous chart:
[
{ orient: "left" },
{ orient: "bottom", tickFormat: d => moment(d).format("MM/DD") }
]
There's no need to pass a tickFormat to the left axis, since the values are simple integers, but if you don't tell it how to display the dates nicely (here using moment.js
) then you'll get terrible labels for your x axis.
From here you might want to:
Add interactivity Add tooltips Add annotations Add a minimap