Mirror histogram
This tutorial is a variation around the general introduction to histogram with react and d3.js. You should probably understand the concepts described there before reading here.
This example explains how to compare the distribution of 2 groups using amirror histogram. One group is displayed above the X axis, the other onebelow. It allows a direct comparison without having any overlap.
A code sandbox is provided for the final result, but explanations target what's different compared to an usual histogram.
Plot and code
If you are in a hurry, this is what we're trying to achieve here.🙇♂️
The distributions of 2 groups are displayed on the same figure, 1 group being on top and the other being below the X axis. It allows to compare them efficiently, with no overlap. .
A mirror histogram made with react and d3.js to compare the distribution of 2 groups in a dataset
The Data
The dataset used here is slightly different as the one used for the simple 1 group histogram.
An array is used, with each object in it providing the name (group
property here) and the values
of a group. Note that if more than 2 items are available in the array, only the 2 first will be used by the component.
Here is a minimal example of the data structure:
const data = [
{
group: "A",
values: [0, 0, 2, 2, 2, 0]
},
{
group: "B",
values: [0, 0, 2, 2, 2, 0]
},
...
];
Building the histogram buckets
The exact same logic as the one used on the 1 group histogram must be used here. But the bucketGenerator
must be run on both groups of the dataset.
Once it is done we'll have use the 2 results to build the top and the bottom histogram charts separately.
const bucketGenerator = useMemo(() => {
return d3
.bin()
.value((d) => d)
.domain(xScale.domain() as [number, number])
.thresholds(xScale.ticks(BUCKET_NUMBER));
}, [xScale]);
const bucketsTop = bucketGenerator(data[0].values);
const bucketsBottom = bucketGenerator(data[1].values);
Distribution
Contact
👋 Hey, I'm Yan and I'm currently working on this project!
Feedback is welcome ❤️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data
with gmail.com
. You can also subscribe to the newsletter to know when I publish more content!