Published
Edited
Mar 30, 2022
10 stars
Insert cell
Insert cell
table(data)
Insert cell
Insert cell
data = FileAttachment("penguins.csv").csv({typed: true})
Insert cell
table = (data) => {
const node = htl.html`<div style=${{
maxHeight: "500px",
overflowY: "scroll"
}}></div>`;

const cols = Object.keys(data[0]);
let sort = cols[0];
let reverse = false;

function setSort(key) {
if (sort === key) {
reverse = !reverse;
} else {
reverse = false;
}
sort = key;
render();
}

function render() {
const sorted = data.sort((_a, _b) => {
let a, b;
if (reverse) {
a = _b;
b = _a;
} else {
a = _a;
b = _b;
}
return typeof a[sort] === "string"
? a[sort].localeCompare(b[sort])
: d3.ascending(a[sort] || 0, b[sort] || 0);
});

const table = htl.html`<table style=${{ maxWidth: "800px", marginTop: 0 }}>
<thead><tr>${cols.map((col) => {
return htl.html`<th
style=${{ cursor: "pointer" }}
onClick=${() => setSort(col)}
><div style=${{ display: "flex" }}>
<div style=${{ color: sort === col ? "black" : "#aaa" }}>${miniplot(
sorted.map((d) =>
typeof d[col] === "string" ? strToNumber(d[col]) : d[col]
)
)}</div>
<span style=${{
paddingLeft: "5px"
}}>${col}</span>
</div></th>`;
})}</tr></thead>
<tbody>
${data.map(
(row) =>
htl.html`<tr>${cols.map(
(col) =>
htl.html`<td style=${{
textAlign: typeof row[col] === "number" ? "right" : "left",
fontVariant: "tabular-nums"
}}>${row[col]}</td>`
)}</tr>`
)}
</tbody>
</table>`;

if (node.querySelector("table"))
node.removeChild(node.querySelector("table"));
node.appendChild(table);
}

render();

return node;
}
Insert cell
miniplot = (data) =>
htl.html`<div style=${{
width: "15px",
height: "15px"
}}>${Plot.areaX(data, { curve: "step-after" }).plot({
width: 100,
height: 100,
x: { axis: false },
y: { axis: false, padding: 0, domain: [data.length - 1, 0] },
marginTop: 0,
marginLeft: 0,
marginBottom: 0,
marginRight: 0
})}</div>`
Insert cell
import {strToNumber} from "@tophtucker/scrapbook"
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