Published
Edited
Jun 21, 2022
2 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function addLoess3( // using the "loess" npm package
array,
{
xKey,
yKey,
xAccessor = (d) => d[xKey],
yAccessor = (d) => d[yKey],
outKey,
bandwidth
}
) {
const filtered = array.filter(
(d) => Number.isFinite(yAccessor(d)) && Number.isFinite(xAccessor(d))
);
const xFiltered = filtered.map(xAccessor);
const y = filtered.map(yAccessor);
const model = new Loess(
{
x: xFiltered,
y
},
{ span: bandwidth }
);
const fit = model.predict();
const fitted = fit.fitted.map((d, i) => ({ index: xFiltered[i], value: d }));
console.log("SLERB", fitted);
return array.map((d) => {
const loessValue = fitted.find((e) => e.index === d.index)?.value ?? null;
return { ...d, [outKey]: loessValue };
});
}
Insert cell
function addLoess2( // Using d3-regression
array,
{
xKey,
yKey,
xAccessor = (d) => d[xKey],
yAccessor = (d) => d[yKey],
outKey,
bandwidth
}
) {
const regressionGenerator = d3Regression
.regressionLoess()
.x(xAccessor)
.y(yAccessor)
.bandwidth(bandwidth);
const loess = regressionGenerator(array);
return array.map((d) => {
const loessValue = loess.find(([index]) => d.index === index)?.[1] ?? null;
return { ...d, [outKey]: loessValue };
});
}
Insert cell
function addLoess( // Using science.js
array,
{
xKey,
yKey,
xAccessor = (d) => d[xKey],
yAccessor = (d) => d[yKey],
outKey = `${yKey}Loess`,
bandwidth = 0.07
}
) {
const loessGenerator = science.stats.loess().bandwidth(bandwidth);
const loess = loessGenerator(array.map(xAccessor), array.map(yAccessor));
return array.map((d, i) => {
const loessValue = loess[i];
return { ...d, [outKey]: loessValue };
});
}
Insert cell
Insert cell
Insert cell
science = require("@sgratzl/science")
Insert cell
Loess = (await import("https://cdn.skypack.dev/loess")).default
Insert cell
d3Regression = require("d3-regression")
Insert cell
import { swatches } from "@d3/color-legend"
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