Create small and sharp charts/components that do one thing one well (e.g. Bars, Lines, Legend, Axis, etc.) and compose them to create complex visualizations.
d3.compose works great with your existing charts (even those from other libraries) and it is simple to extend/customize the built-in charts and components.
When creating complex charts with D3.js and d3.chart, laying out and sizing parts of the chart are often manual processes. With d3.compose, this process is automatic:
- Automatically size and position components
- Layer components and charts by z-index
- Responsive by default, with automatic scaling
- Customizable: d3.compose makes it easy to extend, layout, and refine charts/components
- Reusable: By breaking down visualizations into focused charts and components, you can quickly reconfigure and reuse your code
- Integrated: It's straightforward to use your existing charts or charts from other libraries with d3.compose to create just the chart you're looking for
We'll walk through the steps for creating this chart plotting two series, A and B, for an experiment in the following steps. We'll start with a simple line chart and progressively add components and then switch to bars at the end (to see how easy that is).
Download and add d3.compose (and its dependencies: D3.js and d3.chart) to your page.
2. Add Chart
First, we'll take just the B results and add a line chart to visualize the data.
3. Add y-axis Component
The chart isn't very meaningful without knowing what the values are, so let's add a y-axis to the chart.
4. Add Scales
In the previous step, the y-axis domain coincidentally matched the line chart's scale, but if the line chart's scale needs to be changed (e.g. to given more room at the top of the chart), a scale can be created that is shared between components and charts. Additionally, scales can be created with the domain automatically set from the given data. Next, let's add an x-axis and change the scale for the y-axis.
5. Add Series
With the chart taking shape, let's add another data series: the A results. All of the standard charts handle both single or series data by default and there are helpers and mixins to add series functionality to your custom charts/components.
6. Add Legend
Now that there are multiple series, let's add a legend.
The legend component can take in a
data property to manually create values,
or it can automatically load series information from each chart passed to
charts (by key).
7. Add Titles
Finally, let's add titles to the chart and axes.
8. Switch to Bars
Your colleagues decide they want to see what the chart would look like with bars instead of lines (a potentially major change without d3.compose). Just two things need to change: switch 'Lines' to 'Bars' and the x-scale needs to use an ordinal scale.