Public
Edited
Oct 7, 2024
Insert cell
Insert cell
Insert cell
values1d = [2.1, 2.9, 3.1, 5.7, 6.6, 8.5]
Insert cell
Plot.lineY(values1d, density1d()).plot({
marks: [Plot.crosshairX(values1d, density1d({ x: "point" }))]
})
Insert cell
Insert cell
function density1d(
// Accept the normal output channels that Plot does
// By default, set `x` and `y` to the `point` and `density` channels, but let users override at will
{ z, fill, stroke, x, y, x1, x2, y1, y2 } = { x: "point", y: "density" },
{
// We accept all the options that `fast-kde` does, including a custom `x` channel!
x: inputX,
weight,
bandwidth,
adjust,
extent,
pad,
bins,
...options
} = {}
) {
// Filter to just value (non-null) outputs
const outputs = Object.fromEntries(
Object.entries({ z, fill, stroke, x, y, x1, x2, y1, y2 }).filter(
([key, value]) => value === "point" || value === "density"
)
);

return {
...options,
...outputs,
transform: (data, facets) => {
// Separately compute densities for each facet
const densities = facets.map((facet) => {
// `facet` is a `UInt32Array`, so it needs to be copied before we can use it like this
const facetData = [...facet].map((index) => data[index]);

// `density1d` also needs to be copied to produce (x, y) pairs for our plot
return [
...kde
.density1d(facetData, {
x: inputX,
weight,
bandwidth,
adjust,
extent,
pad,
bins
})
.points("point", "density")
];
});

// Simultaneously flatten the array and compute the new facets

let newData = [];
let newFacets = [];
let index = 0;

for (let density of densities) {
let facet = [];
for (let facetIndex = 0; facetIndex < density.length; facetIndex++) {
newData.push(density[facetIndex]);
facet.push(index);
index++;
}
newFacets.push(facet);
}

return {
data: newData,
facets: newFacets
};
}
};
}
Insert cell
kde = require("fast-kde@^0.2.2")
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more